<?php

namespace Kyranb\Footprints;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;

class Footprinter implements FootprinterInterface
{
    protected Request $request;

    protected string $random;

    public function __construct()
    {
        $this->random = Str::random(20); // Will only be set once during requests since this class is a singleton
    }

    /** @inheritDoc */
    public function footprint(Request $request): string
    {
        $this->request = $request;

        if ($request->hasCookie(config('footprints.cookie_name'))) {
            return $request->cookie(config('footprints.cookie_name'));
        }

        // This will add the cookie to the response
        Cookie::queue(
            config('footprints.cookie_name'),
            $footprint = $this->fingerprint(),
            config('footprints.attribution_duration'),
            null,
            config('footprints.cookie_domain')
        );

        return $footprint;
    }

    /**
     * This method will generate a fingerprint for the request based on the configuration.
     *
     * If relying on cookies then the logic of this function is not important, but if cookies are disabled this value
     * will be used to link previous requests with one another.
     *
     * @return string
     */
    protected function fingerprint()
    {
        // This is highly inspired from the $request->fingerprint() method
        return sha1(implode('|', array_filter([
            $this->request->ip(),
            $this->request->header('user-agent'),
            config('footprints.uniqueness') ? $this->random : null,
        ])));
    }
}

<?php

namespace Kyranb\Footprints;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;

class Footprinter implements FootprinterInterface
{
    protected Request $request;

    protected string $random;

    public function __construct()
    {
        $this->random = Str::random(20); // Will only be set once during requests since this class is a singleton
    }

    /** @inheritDoc */
    public function footprint(Request $request): string
    {
        $this->request = $request;

        if ($request->hasCookie(config('footprints.cookie_name'))) {
            return $request->cookie(config('footprints.cookie_name'));
        }

        // This will add the cookie to the response
        Cookie::queue(
            config('footprints.cookie_name'),
            $footprint = $this->fingerprint(),
            config('footprints.attribution_duration'),
            null,
            config('footprints.cookie_domain')
        );

        return $footprint;
    }

    /**
     * This method will generate a fingerprint for the request based on the configuration.
     *
     * If relying on cookies then the logic of this function is not important, but if cookies are disabled this value
     * will be used to link previous requests with one another.
     *
     * @return string
     */
    protected function fingerprint()
    {
        // This is highly inspired from the $request->fingerprint() method
        return sha1(implode('|', array_filter([
            $this->request->ip(),
            $this->request->header('User-Agent'),
            config('footprints.uniqueness') ? $this->random : null,
        ])));
    }
}

Use proper syntax for User-Agent header

Use proper syntax for User-Agent header


<?php namespace Leean\Endpoints\Inc;

use Leean\Acf\All as Acf;

/**
 * Class Content
 *
 * @package Leean\Endpoints\Inc
 */
class Content
{
	/**
	 * Get the content
	 *
	 * @param Int|\WP_Post $post The post
	 * @return array
	 */
	public static function get( $post ) {
		$post = is_a( $post, 'WP_Post' ) ? $post : get_post( $post );

		$data = [
			'title' => get_the_title( $post ),
			'content' => apply_filters( 'the_content', get_post_field( 'post_content', $post->ID ) ),
		];

		return array_merge( $data, Acf::get_post_fields( $post->ID, false ) );
	}
}

<?php namespace Leean\Endpoints\Inc;

use Leean\Acf;

/**
 * Class Content
 *
 * @package Leean\Endpoints\Inc
 */
class Content
{
	/**
	 * Get the content
	 *
	 * @param Int|\WP_Post $post The post
	 * @return array
	 */
	public static function get( $post ) {
		$post = is_a( $post, 'WP_Post' ) ? $post : get_post( $post );

		$data = [
			'title' => get_the_title( $post ),
			'content' => apply_filters( 'the_content', get_post_field( 'post_content', $post->ID ) ),
		];

		return array_merge( $data, Acf::get_post_field( $post->ID, false ) );
	}
}

Switch to new ACF format

Switch to new ACF format


<?php

namespace WyriHaximus\React\ChildProcess\Messenger;

/**
 * @todo code smell with $source
 */
trait OnDataTrait
{
    /**
     * @var string[]
     */
    protected $buffers = [
        'stdin' => '',
        'stdout' => '',
        'stderr' => '',
    ];
    /**
     * @param string $data
     * @param string $source
     */
    protected function onData($data, $source)
    {
        $this->buffers[$source] .= $data;

        if (strpos($this->buffers[$source], PHP_EOL) !== false) {
            $messages = explode(PHP_EOL, $this->buffers[$source]);
            $this->buffers[$source] = array_pop($messages);
            $this->iterateMessages($messages, $source);
        }
    }

    /**
     * @param array $messages
     * @param string $source
     */
    protected function iterateMessages(array $messages, $source)
    {
        foreach ($messages as $message) {
            $this->handleMessage(json_decode($message, true), $source);
        }
    }

    /**
     * @param array $message
     * @param $source
     * @return void
     */
    abstract protected function handleMessage(array $message, $source);
}

<?php

namespace WyriHaximus\React\ChildProcess\Messenger;

use WyriHaximus\React\ChildProcess\Messenger\Messages\Line;

/**
 * @todo code smell with $source
 */
trait OnDataTrait
{
    /**
     * @var string[]
     */
    protected $buffers = [
        'stdin' => '',
        'stdout' => '',
        'stderr' => '',
    ];
    /**
     * @param string $data
     * @param string $source
     */
    protected function onData($data, $source)
    {
        $this->buffers[$source] .= $data;

        if (strpos($this->buffers[$source], Line::EOL) !== false) {
            $messages = explode(Line::EOL, $this->buffers[$source]);
            $this->buffers[$source] = array_pop($messages);
            $this->iterateMessages($messages, $source);
        }
    }

    /**
     * @param array $messages
     * @param string $source
     */
    protected function iterateMessages(array $messages, $source)
    {
        foreach ($messages as $message) {
            $this->handleMessage(json_decode($message, true), $source);
        }
    }

    /**
     * @param array $message
     * @param $source
     * @return void
     */
    abstract protected function handleMessage(array $message, $source);
}

Use Line::EOL for line detection

Use Line::EOL for line detection


<?php

namespace Scriptotek\Alma\Users;

use Scriptotek\Alma\ResourceList;

class Users extends ResourceList
{
    protected $resourceName = User::class;

    /**
     * Iterates over all users matching the given query.
     * Handles continuation.
     */
    public function search($query, $full = false, $batchSize = 10)
    {
        $offset = 0;
        while (true) {
            $response = $this->client->getJSON('/users', ['q' => $query, 'limit' => $batchSize, 'offset' => $offset]);

            if ($response->total_record_count == 0) {
                break;
            }

            foreach ($response->user as $data) {
                if (strpos($data->primary_id, 'no primary id') === 0) {
                    continue;
                }
                $user = User::fromResponse($this->client, $data);
                if ($full) {
                    $user->fetch();
                }
                yield $user;
                $offset++;
            }
            if ($offset >= $response->total_record_count) {
                break;
            }
        }
    }
}

<?php

namespace Scriptotek\Alma\Users;

use Scriptotek\Alma\ResourceList;

class Users extends ResourceList
{
    protected $resourceName = User::class;

    /**
     * Iterates over all users matching the given query.
     * Handles continuation.
     */
    public function search($query, $full = false, $batchSize = 10)
    {

        // The API will throw a 400 response if you include properly encoded spaces,
        // but underscores work as a substitute.
        $query = str_replace(' ', '_', $query);

        $offset = 0;
        while (true) {
            $response = $this->client->getJSON('/users', ['q' => $query, 'limit' => $batchSize, 'offset' => $offset]);

            if ($response->total_record_count == 0) {
                break;
            }

            foreach ($response->user as $data) {

                // Contacts without a primary identifier will have the primary_id
                // field populated with something weird like "no primary id (123456789023)".
                // We ignore those.
                // See: https://github.com/scriptotek/php-alma-client/issues/6
                if (strpos($data->primary_id, 'no primary id') === 0) {
                    continue;
                }

                $user = User::fromResponse($this->client, $data);
                if ($full) {
                    $user->fetch();
                }
                yield $user;
                $offset++;
            }
            if ($offset >= $response->total_record_count) {
                break;
            }
        }
    }
}

Fix for spaces in user queries

Fix for spaces in user queries


<?php

define("DB_Hostname", "148.72.232.125");
		define("DB_Username", "studio_gsp2015");
		define("DB_Password", "Studio@123");
		define("DB_databasename", "gsp_2015");

$link = mysql_connect(DB_Hostname, DB_Username, DB_Password) or die('Error connecting to mysql');
$mysql_db = mysql_select_db(DB_databasename, $link);
?>

<?php

define("DB_Hostname", "43.255.154.31");
		define("DB_Username", "studio_gsp2015");
		define("DB_Password", "Studio@123");
		define("DB_databasename", "gsp_2015");

$link = mysql_connect(DB_Hostname, DB_Username, DB_Password) or die('Error connecting to mysql');
$mysql_db = mysql_select_db(DB_databasename, $link);
?>

Change Ip address in website file

Change Ip address in website file

Ip Addresss


<?php
	namespace Bolt\Api\Request;

	use Bolt\Base;
	use Bolt\Arrays;
	use function Cruxoft\dump;

	class InputMask extends Base
	{
		public $name;
		public $type;
		public $children = array();
		public $options = array();

		public function __construct($data = null)
		{
			parent::__construct($data);
		}

		public function add($name, $type = null, $options = array())
		{
			$structure = array(
				"name" => $name,
				"type" => $type,
				"options" => $options
			);
			$this->children[] = new InputMask($structure);

			return $this;
		}

		public function inflate($fields)
		{
			foreach ($fields as $key => $value)
			{
				if (Arrays::type($fields) === "numeric" || is_integer($key))
				{
					$this->add($value);
				}
				else
				{
					$mask = new InputMask();
					$mask->name($key);
					$mask->inflate($value);
					$this->children[] = $mask;
				}
			}

			return $this;
		}
	}
?>

<?php
	namespace Bolt\Api\Request;

	use Bolt\Base;
	use Bolt\Arrays;
	use function Cruxoft\dump;

	class InputMask extends Base
	{
		public $name;
		public $type;
		public $children = array();
		public $options = array();

		public function __construct($data = null)
		{
			parent::__construct($data);
		}

		public function add($name, $type = null, $options = array())
		{
			$structure = array(
				"name" => $name,
				"type" => $type,
				"options" => $options
			);
			$this->children[] = new InputMask($structure);

			return $this;
		}

		public function inflate($fields)
		{
			foreach ($fields as $key => $value)
			{
				if (Arrays::type($fields) === "numeric" || is_integer($key))
				{
					$this->add($value, null, ["required" => true]);
				}
				else
				{
					$mask = new InputMask();
					$mask->name($key);
					$mask->inflate($value);
					$mask->options(["required" => true]);
					$this->children[] = $mask;
				}
			}

			return $this;
		}
	}
?>

Set 'required' to true in inflate

Set 'required' to true in inflate


<?php namespace Limoncello\Flute\Types;

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

use DateTimeImmutable;
use JsonSerializable;

/**
 * Wrapper class for `DateTimeInterface` value with JSON serialization support.
 *
 * @package Limoncello\Flute
 */
class DateTime extends DateTimeImmutable implements JsonSerializable
{
    /** DateTime format */
    const JSON_API_FORMAT = self::ISO8601;

    /**
     * @inheritdoc
     */
    public function jsonSerialize()
    {
        return $this->format(static::JSON_API_FORMAT);
    }
}

<?php namespace Limoncello\Flute\Types;

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

use DateTimeImmutable;
use JsonSerializable;

/**
 * Wrapper class for `DateTimeInterface` value with JSON serialization support.
 *
 * @package Limoncello\Flute
 */
class DateTime extends DateTimeImmutable implements JsonSerializable
{
    /** DateTime format */
    const JSON_API_FORMAT = \DateTime::ISO8601;

    /**
     * @inheritdoc
     */
    public function jsonSerialize()
    {
        return $this->format(static::JSON_API_FORMAT);
    }
}

Fix format constant for PHP 7.1

Fix format constant for PHP 7.1


<?php

namespace Calendar\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Scarlett\Controller\Controller;
use Calendar\Model\LeapYear;

class LeapYearController extends Controller
{
    public function indexAction(Request $request, $year)
    {
        $leapyear = new LeapYear();
        if ($leapyear->isLeapYear($year)) {
            $message = 'Yep, this is a leap year!';
        }else{
            $message = 'Nope, this is not a leap year!';
        }

        return $this->render('leapYear', array('message' => $message));
    }

    public function primeAction(Request $request, $number)
    {
        if($number%$number == 0  && $number%1 == 0){
            $message = 'Prime number';
        }else{
            $message = 'Not prime';
        }

        return $this->render('primeNumber', array('message' => $message));
    }
}

<?php

namespace Calendar\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Scarlett\Controller\Controller;
use Calendar\Model\LeapYear;

class LeapYearController extends Controller
{
    public function indexAction(Request $request, $year)
    {
        $leapyear = new LeapYear();
        if ($leapyear->isLeapYear($year)) {
            $message = 'Yep, this is a leap year!';
        }else{
            $message = 'Nope, this is not a leap year!';
        }

        return $this->render('leapYear', array('message' => $message));
    }

    public function primeAction(Request $request, $number)
    {
        $message = "It's prime!";
        for($i=$number-1;$i>=2;$i--) {
            if($number%$i == 0) {
                $message =" It's not prime!";
                break;
            }
        }

        return $this->render('primeNumber', array('message' => $message));
    }
}

Add a real prime number test

Add a real prime number test


<?php
namespace Composer\Installers;

/**
 * An installer to handle TYPO3 Flow specifics when installing packages.
 */
class TYPO3FlowInstaller extends BaseInstaller
{
    protected $locations = array(
        'package'   => 'Packages/Application/{$name}/',
        'framework' => 'Packages/Framework/{$name}/',
        'plugin'    => 'Packages/Plugins/{$name}/',
        'site'      => 'Packages/Sites/{$name}/',
        'build'     => 'Build/{$name}/',
    );
}

<?php
namespace Composer\Installers;

/**
 * An installer to handle TYPO3 Flow specifics when installing packages.
 */
class TYPO3FlowInstaller extends BaseInstaller
{
    protected $locations = array(
        'package'   => 'Packages/Application/{$name}/',
        'framework' => 'Packages/Framework/{$name}/',
        'plugin'    => 'Packages/Plugins/{$name}/',
        'site'      => 'Packages/Sites/{$name}/',
        'build'     => 'Build/{$name}/',
    );

	/**
	 * Modify the package name to be a TYPO3 Flow style key.
	 *
	 * @param array $vars
	 * @return array
	 */
	public function inflectPackageVars($vars)
	{
		$autoload = $this->package->getAutoload();
		if (isset($autoload['psr-0']) && is_array($autoload['psr-0']))
		{
			$namespace = key($autoload['psr-0']);
			$vars['name'] = str_replace('\\', '.', $namespace);
		}
		return $vars;
	}
}

Add inflection of package names for TYPO3 Flow / Neos. Closes GH-56.


<?php
if(!function_exists('FoundationPress_entry_meta')) :
    function FoundationPress_entry_meta() {
        echo '<time class="updated" datetime="'. get_the_time('c') .'">'. sprintf(__('Posted on %s at %s.', 'FoundationPress'), get_the_time('l, F jS, Y'), get_the_time()) .'</time>';
        echo '
'. __('Written by', 'FoundationPress') .' '. get_the_author() .'
';
    }
endif;
?>

<?php
if(!function_exists('FoundationPress_entry_meta')) :
    function FoundationPress_entry_meta() {
        echo '<time class="updated" datetime="'. get_the_time('c') .'">'. sprintf(__('Posted on %s at %s.', 'FoundationPress'), get_the_date(), get_the_time()) .'</time>';
        echo '
'. __('Written by', 'FoundationPress') .' '. get_the_author() .'
';
    }
endif;
?>

Format time and date according to WordPress settings.

Removed the hardcoded time formatting, to make the theme honor the time and date settings set in the WordPress Admin


<?php

namespace Lily\Application;

class MiddlewareApplication
{
    private $application;
    private $middleware;

    public function __construct(array $pipeline)
    {
        $this->handler = array_shift($pipeline);
        $this->middleware = $pipeline;
    }

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

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

    public function __invoke($request)
    {
        $handler = $this->handler();

        foreach ($this->middleware() as $_mw) {
            $handler = $_mw($handler);
        }

        return $handler($request);
    }
}

<?php

namespace Lily\Application;

class MiddlewareApplication
{
    private $handler;
    private $middleware;

    public function __construct(array $pipeline)
    {
        $this->handler = array_shift($pipeline);
        $this->middleware = $pipeline;
    }

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

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

    public function __invoke($request)
    {
        $handler = $this->handler();

        foreach ($this->middleware() as $_mw) {
            $handler = $_mw($handler);
        }

        return $handler($request);
    }
}

Rename private variable to $handler

Rename private variable to $handler


<?php

namespace League\Event;

class BufferedEmitter extends Emitter
{
    /**
     * @var EventInterface[]
     */
    protected $bufferedEvents = [];

    /**
     * @inheritdoc
     */
    public function emit($event)
    {
        $this->bufferedEvents[] = $event;

        return $event;
    }

    /**
     * @inheritdoc
     */
    public function emitBatch(array $events)
    {
        foreach($events as $event) {
            $this->bufferedEvents[] = $event;
        }

        return $events;
    }

    /**
     * Emit the buffered events.
     *
     * @return array
     */
    public function emitBufferedEvents()
    {
        $result = [];

        foreach($this->bufferedEvents as $event) {
            $result[] = parent::emit($event);
        }

        return $result;
    }
}

<?php

namespace League\Event;

class BufferedEmitter extends Emitter
{
    /**
     * @var EventInterface[]
     */
    protected $bufferedEvents = [];

    /**
     * @inheritdoc
     */
    public function emit($event)
    {
        $this->bufferedEvents[] = $event;

        return $event;
    }

    /**
     * @inheritdoc
     */
    public function emitBatch(array $events)
    {
        foreach ($events as $event) {
            $this->bufferedEvents[] = $event;
        }

        return $events;
    }

    /**
     * Emit the buffered events.
     *
     * @return array
     */
    public function emitBufferedEvents()
    {
        $result = [];

        foreach ($this->bufferedEvents as $event) {
            $result[] = parent::emit($event);
        }

        return $result;
    }
}

Fix for PSR2 spacing around foreach keyword


<title>Number Counter</title>

<?php

  $date = $_GET['date'];

	if (!isset($num)) die("Give me a number boo");
	if ($num < 0) die ("Yo, digits are not valid, bro...");

	$num = $numend;

echo "
Counting towards ".$date.":"."
";

			for ($num=$numend; $numend>=0; $numend++)
			{
			echo $numend."
";
			}

print "

";

echo "
Counting backwards from ".$numend.":"."
";
print "
";

			for ($num=$numend; $num>=$numstart; $num--)
			{

			echo $num."
";
			}
	?>

<title>Number Counter</title>

<?php

  $date = $_GET['date'];

	if (!isset($num)) die("Give me a number boo");
	if ($num < 0) die ("Yo, digits are not valid, bro...");

	$num = $numend;

echo "
Counting towards ".$num.":"."
";

			for ($num=$numend; $numend>=0; $numend++)
			{
			echo $numend."
";
			}

print "

";

echo "
Counting backwards from ".$numend.":"."
";
print "
";

			for ($num=$numend; $num>=$numstart; $num--)
			{

			echo $num."
";
			}
	?>

Correct variables, and have it add to number given in get request.


<?php
// Path constants
define('DS', DIRECTORY_SEPARATOR);
define('PS', PATH_SEPARATOR);
define('BP', dirname(__FILE__));

// Display errors
ini_set('display_errors', 1);

// Set error reporting level
error_reporting(E_ALL | E_STRICT);

// Add include paths
$paths = array();
$paths[] = BP.DS.'app';

$appPath = implode(PS, $paths);
set_include_path($appPath . PS . get_include_path());

// Initialize and run the app
include 'Core/Bootstrap.php';
$bootstrap = new \Webaholicson\Minimvc\Core\Bootstrap();
$app = $bootstrap->init();
$app->run();

<?php
// Path constants
define('DS', DIRECTORY_SEPARATOR);
define('PS', PATH_SEPARATOR);
define('BP', dirname(__FILE__));

// Display errors
ini_set('display_errors', 1);

// Set error reporting level
error_reporting(E_ALL | E_STRICT);

// Add include paths
$paths = array();
$paths[] = BP.DS.'app';

$appPath = implode(PS, $paths);
set_include_path($appPath . PS . get_include_path());

// Initialize and run the app
include 'Core/Services.php';
include 'Core/Bootstrap.php';
$manager = new \Webaholicson\Minimvc\Core\Services();
$bootstrap = new \Webaholicson\Minimvc\Core\Bootstrap($manager);
$app = $bootstrap->init();
$app->run();

Include services and pass to bootstrapper


<?php include("lib/index.php");

//Load layout for displaying single image
if($layout->isImage()) {
	$f = "themes/".$layout->getTheme()."/single.php";

	if(!file_exists($f)) {
		print 'Could not load theme file for single image.';
		return;
	}

	include $f;
	return;
}

//Load layout for displaying content listing
$f = "themes/".$layout->getTheme()."/listing.php";

if(!file_exists($f)) {
	print 'Could not load theme file for listing.';
	return;
}

include $f;
return;

?>

<?php

//Fake the working directory so that including will be handled properly
$sfg_chdir = getcwd();
chdir(dirname(__FILE__));

include("lib/index.php");

//Load layout for displaying single image
if($layout->isImage()) {
	$f = "themes/".$layout->getTheme()."/single.php";

	if(!file_exists($f)) {
		print 'Could not load theme file for single image.';
		return;
	}

	include $f;
	return;
}

//Load layout for displaying content listing
$f = "themes/".$layout->getTheme()."/listing.php";

if(!file_exists($f)) {
	print 'Could not load theme file for listing.';
	return;
}

include $f;

//Work done, change back to previous workdir
chdir($sfg_chdir);

?>

Fix inclusion when embedding the file from outside world.


<?php

get_header();

if (!is_front_page()) :

    if (have_posts()) :

        ?>

                <?php get_template_part(SNIPPETS_DIR . '/header/page-header'); ?>

                    <?php

                    /* Start the Loop */
                    while (have_posts()) :
                        the_post();

                        if (is_page()) :
                            get_template_part(SNIPPETS_DIR . '/content/content-page');
                        else :
                            get_template_part(SNIPPETS_DIR . '/content/content');
                        endif;

                    endwhile;

                    ?>

                <?php

            else :

                get_template_part(SNIPPETS_DIR . '/content/content-none');

            endif;

            ?>

                    <?php get_template_part(SNIPPETS_DIR . '/navigation/pagination'); ?>

            <?php get_template_part(SNIPPETS_DIR . '/sidebars/twitter-content'); ?>

    <?php

endif;

get_sidebar();

get_footer();

<?php

$pagination_wrapper_start = '

';
$pagination_wrapper_end = '

';

if (is_author()):
    $pagination_wrapper_start = '';
    $pagination_wrapper_end = '';
endif;

get_header();

if (!is_front_page()) :

    if (have_posts()) :

        ?>

                <?php get_template_part(SNIPPETS_DIR . '/header/page-header'); ?>

                    <?php

                    /* Start the Loop */
                    while (have_posts()) :
                        the_post();

                        if (is_page()) :
                            get_template_part(SNIPPETS_DIR . '/content/content-page');
                        else :
                            get_template_part(SNIPPETS_DIR . '/content/content');
                        endif;

                    endwhile;

                    ?>

                <?php

            else :

                get_template_part(SNIPPETS_DIR . '/content/content-none');

            endif;

            echo $pagination_wrapper_start;
            get_template_part(SNIPPETS_DIR . '/navigation/pagination');
            echo $pagination_wrapper_end;

            get_template_part(SNIPPETS_DIR . '/sidebars/twitter-content');

            ?>

    <?php

endif;

get_sidebar();

get_footer();

Make pagination wrappers conditional for author template


<?php

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

$app->run();

<?php

/** @var \Bolt\Application $app */
$app = require_once __DIR__ . '/app/load.php';

$app->run();

Annotate $app type in front controller

Annotate $app type in front controller


<?php

namespace Conner\Tagging\Console\Commands;

use Conner\Tagging\TaggingUtility;
use Conner\Tagging\Model\TagGroup;
use Illuminate\Console\Command;

class GenerateTagGroup extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tagging:create-group {group_name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a laravel tag group';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $groupName = $this->argument('group_name');

        $tagGroup = new TagGroup();
        $tagGroup->name = $groupName;
        $tagGroup->slug = TaggingUtility::normalize($groupName);

        $tagGroup->save();

        $this->info('Created tag group: ' . $groupName);
    }
}

<?php

namespace Conner\Tagging\Console\Commands;

use Conner\Tagging\TaggingUtility;
use Conner\Tagging\Model\TagGroup;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;

class GenerateTagGroup extends Command
{
    protected $name = 'tagging:create-group';

    protected $signature = 'tagging:create-group {group}';

    protected $description = 'Create a laravel tag group';

    public function handle()
    {
        $groupName = $this->argument('group');

        $tagGroup = new TagGroup();
        $tagGroup->name = $groupName;
        $tagGroup->slug = TaggingUtility::normalize($groupName);

        $tagGroup->save();

        $this->info('Created tag group: '.$groupName);
    }

    protected function getArguments()
    {
        return [
            ['group', InputArgument::REQUIRED, 'Name of the group to create.'],
        ];
    }
}

Make create tag group more compatible with older laravel


<?php

namespace Despark\Cms\Models;

use Despark\Cms\Admin\Traits\AdminModelTrait;
use Spatie\Permission\Models\Role as RoleModel;

class Role extends RoleModel
{
    use AdminModelTrait;

    public $identifier = 'role';

    protected $rules = [
        'name' => 'required|unique:roles|max:255',
    ];

    protected $rulesUpdate = [
        'name' => 'required|max:255',
    ];

    public function getPermissions()
    {
        return Permission::all()->pluck('name', 'name')->toArray();
    }
}

<?php

namespace Despark\Cms\Models;

use Despark\Cms\Admin\Traits\AdminModelTrait;
use Spatie\Permission\Models\Role as RoleModel;

class Role extends RoleModel
{
    use AdminModelTrait;

    public $identifier = 'role';

    protected $rules = [
        'name' => 'required|unique:roles|max:255',
    ];

    protected $rulesUpdate = [
        'name' => 'required|max:255',
    ];

    protected static function getPermissions()
    {
        return Permission::all()->pluck('name', 'name')->toArray();
    }
}

Make get permissions protected static (probably updated package)


<?php if ( !defined( 'HABARI_PATH' ) ) { die('No direct access'); } ?>

		Github
		Twitter
		Habari Project

Fix the Habari Trac link so it doesn't include a hardcoded date.


<?php  namespace php\decoratorPattern;

class Keyboard extends HardwareDecorator{
	protected $hardware;

	public function __construct(Hardware $hardware){
		$this->hardware = $hardware;
	}

	/**
	* Get decription of hardware
	*
	* @return string
	*/
	public function getDescription(){
		$this->description .= $this->hardware->getDescription().' + keyboard';

		return $this->description;
	}

	/**
	* Get cost of hardware
	*
	* @return int
	*/
	public function cost(){

		return $this->hardware->cost()+60;
	}
}

<?php  namespace php\decoratorPattern;

class Keyboard extends HardwareDecorator{
	protected $hardware;

	public function __construct(Hardware $hardware){
		$this->hardware = $hardware;
	}

	/**
	* Gets decription of hardware
	*
	* @return string
	*/
	public function getDescription(){
		$this->description .= $this->hardware->getDescription().' + keyboard';

		return $this->description;
	}

	/**
	* Gets cost of hardware
	*
	* @return int
	*/
	public function cost(){

		return $this->hardware->cost()+60;
	}
}

Add third person declarative to phpdoc

Add third person declarative to phpdoc


<?php
/*
Plugin Name: TypoFR
Plugin URI: https://github.com/borisschapira/typofr
Description: a plugin for french typography management, powered by JoliTypo
Version: 0.1
Author: Boris Schapira
Author URI: http://borisschapira.com
License: MIT
*/

include 'vendor/autoload.php';

// Correction typographique francaise par JoliTypo

use JoliTypo\Fixer;

function typofr($text)
{
    static $fixer;
    if (!isset($fixer)) {
        $fixer = new Fixer(array(
            'Ellipsis',
            'Dimension',
            'Dash',
            'FrenchQuotes',
            'FrenchNoBreakSpace',
            'CurlyQuote',
            'Hyphen',
            'Trademark'));
        $fixer->setLocale('fr_FR'); // Needed by the Hyphen Fixer
    }

    $decoded = utf8_decode($text);
    $reEncoded = utf8_encode($decoded);

    $fixed = $fixer->fix($decoded);
    $fixedWrong = $fixer->fix($reEncoded);

    $logs = "<script> console && console.log('-------\\nOriginal : ".$text." (".mb_detect_encoding($text).")\\nDecoded : ".$decoded." (".mb_detect_encoding($decoded).")\\nRe-encoded : ".$reEncoded." (".mb_detect_encoding($reincoded).")\\nFix(Decoded) : ".$fixed." (".mb_detect_encoding($fixed).")\\nFix(Re-encoded) : ".$fixedWrong." (".mb_detect_encoding($fixedWrong).")')</script>";

    return $fixed.$logs;
}

//add_filter('the_content', 'typofr');
add_filter('the_title', 'typofr');

<?php
/*
Plugin Name: TypoFR
Plugin URI: https://github.com/borisschapira/typofr
Description: a plugin for french typography management, powered by JoliTypo
Version: 0.1
Author: Boris Schapira
Author URI: http://borisschapira.com
License: MIT
*/

include 'vendor/autoload.php';

// Correction typographique francaise par JoliTypo

use JoliTypo\Fixer;

function typofr($text)
{
    static $fixer;
    if (!isset($fixer)) {
        $fixer = new Fixer(array(
            'Ellipsis',
            'Dimension',
            'Dash',
            'FrenchQuotes',
            'FrenchNoBreakSpace',
            'CurlyQuote',
            'Hyphen',
            'Trademark'));
        $fixer->setLocale('fr_FR'); // Needed by the Hyphen Fixer
    }

    $fixed = $fixer->fix($decoded);

    return $fixed;
}

add_filter('the_content', 'typofr');
add_filter('the_title', 'typofr');

Remove logs and useless variables

Remove logs and useless variables

git-svn-id: 67b257ddc67a36dd158497794aa97a8ea033a564@929598 b8457f37-d9ea-0310-8a92-e5e31aec5664


<?php

namespace Oro\Bundle\ActionBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ButtonsWidgetController extends Controller
{
    /**
     * @Route("/buttons", name="oro_action_buttons_widget_buttons")
     * @Template()
     *
     * @return array
     */
    public function buttonsAction()
    {
        $buttonProvider = $this->get('oro_action.provider.button');
        $buttonSearchContextProvider = $this->get('oro_action.provider.button_search_context');
        $buttonSearchContext = $buttonSearchContextProvider->getButtonSearchContext();

        return [
            'buttons' => $buttonProvider->findAll($buttonSearchContext),
            'searchContext' => $buttonSearchContext,
        ];
    }
}

<?php

namespace Oro\Bundle\ActionBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ButtonsWidgetController extends Controller
{
    /**
     * @Route("/buttons", name="oro_action_buttons_widget_buttons")
     * @Template()
     *
     * @return array
     */
    public function buttonsAction()
    {
        $buttonProvider = $this->get('oro_action.provider.button');
        $buttonSearchContextProvider = $this->get('oro_action.provider.button_search_context');
        $buttonSearchContext = $buttonSearchContextProvider->getButtonSearchContext();

        return [
            'buttons' => $buttonProvider->findAll($buttonSearchContext),
        ];
    }
}

BAP-12479: Create new widget controller buttonsAction
- Removed unnecessary options.


<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof NotFoundHttpException) {
            // 404 error.
            $resp = new Response();
            $resp->setStatusCode(404);
            $resp->setContent('');
            return $resp;
        }

        return parent::render($request, $e);
    }
}

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        // Convert model not found exceptions to 404 not found exceptions.
        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }

        if ($e instanceof NotFoundHttpException) {
            // 404 error.
            $resp = new Response();
            $resp->setStatusCode(404);
            $resp->setContent('');
            return $resp;
        }

        return parent::render($request, $e);
    }
}


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * PhoneVerified
 */
class PhoneVerified
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $phone;

    /**
     * @var \DateTime
     */
    private $timestamp;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set phone
     *
     * @param string $phone
     * @return PhoneVerified
     */
    public function setPhone($phone)
    {
        $this->phone = $phone;

        return $this;
    }

    /**
     * Get phone
     *
     * @return string
     */
    public function getPhone()
    {
        return $this->phone;
    }

    /**
     * Set timestamp
     *
     * @param \DateTime $timestamp
     * @return PhoneVerified
     */
    public function setTimestamp($timestamp)
    {
        $this->timestamp = $timestamp;

        return $this;
    }

    /**
     * Get timestamp
     *
     * @return \DateTime
     */
    public function getTimestamp()
    {
        return $this->timestamp;
    }
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * PhoneVerified
 *
 * @ORM\Entity
 * @ORM\Table(name="phone_verified")
 */
class PhoneVerified
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $phone;

    /**
     * @var string
     */
    private $email;

    /**
     * @var \DateTime
     */
    private $timestamp;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set phone
     *
     * @param string $phone
     * @return PhoneVerified
     */
    public function setPhone($phone)
    {
        $this->phone = $phone;

        return $this;
    }

    /**
     * Get phone
     *
     * @return string
     */
    public function getPhone()
    {
        return $this->phone;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return PhoneVerified
     */
    public function setEmail($email)
    {
    	$this->email = $email;

    	return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
    	return $this->email;
    }

    /**
     * Set timestamp
     *
     * @param \DateTime $timestamp
     * @return PhoneVerified
     */
    public function setTimestamp($timestamp)
    {
        $this->timestamp = $timestamp;

        return $this;
    }

    /**
     * Get timestamp
     *
     * @return \DateTime
     */
    public function getTimestamp()
    {
        return $this->timestamp;
    }
}

Implement new methods for entify phone verified


<?php namespace Flarum\Extend;

use Illuminate\Foundation\Application;
use Closure;

class Relationship implements ExtenderInterface
{
    protected $parent;

    protected $type;

    protected $name;

    protected $child;

    public function __construct($parent, $type, $name, $child = null)
    {
        $this->parent = $parent;
        $this->type = $type;
        $this->name = $name;
        $this->child = $child;
    }

    public function extend(Application $app)
    {
        $parent = $this->parent;

        $parent::addRelationship($this->name, function ($model) {
            if ($this->type instanceof Closure) {
                return $this->type($model);
            } elseif ($this->type === 'belongsTo') {
                return $model->belongsTo($this->child, null, null, $this->name);
            } else {
                // @todo
            }
        });
    }
}

<?php namespace Flarum\Extend;

use Illuminate\Foundation\Application;
use Closure;

class Relationship implements ExtenderInterface
{
    protected $parent;

    protected $type;

    protected $name;

    protected $child;

    public function __construct($parent, $type, $name, $child = null)
    {
        $this->parent = $parent;
        $this->type = $type;
        $this->name = $name;
        $this->child = $child;
    }

    public function extend(Application $app)
    {
        $parent = $this->parent;

        $parent::addRelationship($this->name, function ($model) {
            if ($this->type instanceof Closure) {
                return call_user_func($this->type, $model);
            } elseif ($this->type === 'belongsTo') {
                return $model->belongsTo($this->child, null, null, $this->name);
            } else {
                // @todo
            }
        });
    }
}

Fix error on discussion page

Fix error on discussion page


<?php

namespace Kregel\FormModel;

class FormModel
{
    public static function using($string)
    {
        switch ($string) {
            case 'bootstrap':
                return new Frameworks\Bootstrap();
            case 'materialize':
                return new Frameworks\Materialize();
            default:
                $custom_thing = config('kregel.formmodel.using.custom-framework');

                return call_user_func($custom_thing);
        }
    }
}

<?php

namespace Kregel\FormModel;

class FormModel
{
    public static function using($string)
    {
        switch ($string) {
            case 'bootstrap':
                return new Frameworks\Bootstrap();
            case 'materialize':
                return new Frameworks\Materialize();
            case 'plain':
                return new Frameworks\Plain();
            default:
                $custom_thing = config('kregel.formmodel.using.custom-framework');
                return call_user_func($custom_thing);
        }
    }
}

Update formmodel with plain using case

Update formmodel with plain using case


<?php

/**
 * @file
 * An Apple News Document Music.
 */

namespace ChapterThree\AppleNews\Document\Components;

/**
 * An Apple News Document Music.
 */
class Music extends Audio {

  /**
   * Implements __construct().
   *
   * @param mixed $role
   *   Role.
   * @param mixed $url
   *   URL.
   * @param mixed $identifier
   *   Identifier.
   */
  public function __construct($role, $url, $identifier = NULL) {
    parent::__construct('music', $identifier);
    $this->setUrl($url);
  }

}

<?php

/**
 * @file
 * An Apple News Document Music.
 */

namespace ChapterThree\AppleNews\Document\Components;

/**
 * An Apple News Document Music.
 */
class Music extends Audio {

  /**
   * Implements __construct().
   *
   * @param mixed $url
   *   URL.
   * @param mixed $identifier
   *   Identifier.
   */
  public function __construct($url, $identifier = NULL) {
    parent::__construct('music', $url, $identifier);
  }

}

Fix Audio component parameter issue.

Fix Audio component parameter issue.


<?php

namespace PoGoPHP\Location;

use GuzzleHttp\Exception\GuzzleException;
use PoGoPHP\Http\HttpClientAwareInterface;
use PoGoPHP\Http\HttpClientAwareTrait;

class LocationSearcher implements HttpClientAwareInterface
{
    use HttpClientAwareTrait;

    public static $maps_url = 'https://maps.google.com/maps/api/geocode/json';

    /**
     * @param  string $location
     * @return Location
     * @throws LocationException
     */
    public function search($location)
    {
        try {
            $response = $this->httpClient->request('GET', (static::$maps_url . '?' . http_build_query(['address' => $location])));
        } catch (GuzzleException $e) {
            throw new LocationException("Error while trying to get location: {$e->getMessage()}", $e->getCode());
        }

        $data = json_decode($response->getBody());

        if ($data === null) {
            throw new LocationException('Received invalid or null data from Google Maps');
        }

        return new Location(
            $data->results[0]->geometry->location->lat,
            $data->results[0]->geometry->location->lng
        );
    }
}

<?php

namespace PoGoPHP\Location;

use GuzzleHttp\Exception\GuzzleException;
use PoGoPHP\Http\HttpClientAwareInterface;
use PoGoPHP\Http\HttpClientAwareTrait;

class LocationSearcher implements HttpClientAwareInterface
{
    use HttpClientAwareTrait;

    public static $maps_url = 'https://maps.google.com/maps/api/geocode/json';

    /**
     * @param  string $location
     * @return Location
     * @throws LocationException
     */
    public function search($location)
    {
        try {
            $response = $this->httpClient->request('GET', (static::$maps_url . '?' . http_build_query(['address' => $location])));
        } catch (GuzzleException $e) {
            throw new LocationException("Error while trying to get location: {$e->getMessage()}", $e->getCode());
        }

        $data = json_decode($response->getBody());

        if ($data === null) {
            throw new LocationException('Received invalid or null data from Google Maps');
        }

        if (empty($data->results)) {
            throw new LocationException("Location '{$location}' not found");
        }

        return new Location(
            $data->results[0]->geometry->location->lat,
            $data->results[0]->geometry->location->lng
        );
    }
}

Add check for valid location

Add check for valid location


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

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

$jql = file_get_contents('php://stdin');

$flags        = new donatj\Flags;
$drop         =& $flags->bool('drop', false, 'Include DROP TABLE?');
$inputComment =& $flags->bool('input-comment', false, 'Include original input as a comment?');

$columnFactory = new \donatj\Misstep\ColumnFactory;

try {
	$flags->parse();
} catch( Exception $e ) {
	echo $e->getMessage() . "\n";
	echo $flags->getDefaults();

	die(1);
}

try {
	if( trim($jql) == '' ) {
		return '';
	}

	$parser   = new \donatj\Misstep\Parser($columnFactory);
	$renderer = new \donatj\Misstep\Renderer($jql, $inputComment, $drop);

	$tables = $parser->parse($jql);
	echo $renderer->render($tables);
} catch( \donatj\Misstep\Exceptions\UserException $e ) {
	fwrite(STDERR, "Error: " . $e->getMessage() . "\n");

	die(1);
}

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

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

$flags        = new donatj\Flags;
$drop         =& $flags->bool('drop', false, 'Include DROP TABLE?');
$inputComment =& $flags->bool('input-comment', false, 'Include original input as a comment?');

$columnFactory = new \donatj\Misstep\ColumnFactory;

try {
	$flags->parse();
} catch( Exception $e ) {
	echo $e->getMessage() . "\n";
	echo $flags->getDefaults();

	die(1);
}

$jql = file_get_contents('php://stdin');

try {
	if( trim($jql) == '' ) {
		return '';
	}

	$parser   = new \donatj\Misstep\Parser($columnFactory);
	$renderer = new \donatj\Misstep\Renderer($jql, $inputComment, $drop);

	$tables = $parser->parse($jql);
	echo $renderer->render($tables);
} catch( \donatj\Misstep\Exceptions\UserException $e ) {
	fwrite(STDERR, "Error: " . $e->getMessage() . "\n");

	die(1);
}

Read flags before standard input

Read flags before standard input


<?php

ob_start();

/**
 * Initialize some variables
 */
$view_data = array();
$title = '';
$description = '';
$css_files = array('header' => array(), 'footer' => array());
$js_files = array('header' => array(), 'footer' => array());

include('config.php');

include('routing.php');

require('functions.php');

// Load the controller
include(__DIR__ . DIRECTORY_SEPARATOR . $controller);

// Stop execution if there's no view
if(empty($view)) {
	exit;
}

// Don't try to load a non existant view
if(!is_file(__DIR__ . DIRECTORY_SEPARATOR . "views" . DIRECTORY_SEPARATOR . "$view.php")) {
	$view = '404';
}

include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."header.php");

extract($view_data);
include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."$view.php");

include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."footer.php");

ob_end_flush();

<?php

ob_start();

/**
 * Initialize some variables
 */
$view_data = array();
$title = '';
$description = '';
$css_files = array('header' => array(), 'footer' => array());
$js_files = array('header' => array(), 'footer' => array());

include('config.php');

include('routing.php');

require('functions.php');

// Load the controller
$extra = include(__DIR__ . DIRECTORY_SEPARATOR . $controller);

if(isset($extra['response_type'])){
	switch($extra['response_type']) {
		case 'json':
			header('Content-type: application/json');
			echo $extra['response'];
			break;
		case 'file':
			break;
		case 'html':
			// There should be a $view defined
		default:
			break;
	}
}

// Stop execution if there's no view
if(empty($view)) {
	exit;
}

// Don't try to load a non existant view
if(!is_file(__DIR__ . DIRECTORY_SEPARATOR . "views" . DIRECTORY_SEPARATOR . "$view.php")) {
	$view = '404';
}

if(isset($extra['no_header']) OR !$extra['no_header']) {
	include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."header.php");
}

extract($view_data);
include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."$view.php");
if(isset($extra['no_footer']) OR !$extra['no_footer']) {
	include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."footer.php");
}

ob_end_flush();

Add response types for controllers and an option to not include the header and footer.


<?php
namespace MongoMonitoring;

require dirname(__DIR__) . '/vendor/autoload.php';

use Icicle\Awaitable;
use Icicle\Coroutine;
use Icicle\Loop;
use Icicle\Socket;
use Icicle\Stream\MemoryStream;
use Icicle\WebSocket\Server\Server;
use MongoDB;
use MongoMonitoring\Server\ApplicationRequestHandler;
use Nette\Neon\Neon;

$configPath = '../config.neon';

$config = Neon::decode(loadFile($configPath));
$server = new Server(new ApplicationRequestHandler($config['hosts'], new MemoryStream()));
$server->listen(9900);

Loop\run();

<?php
namespace MongoMonitoring;

require dirname(__DIR__) . '/vendor/autoload.php';

use Icicle\Awaitable;
use Icicle\Coroutine;
use Icicle\Loop;
use Icicle\Socket;
use Icicle\Stream\MemoryStream;
use Icicle\WebSocket\Server\Server;
use MongoDB;
use MongoMonitoring\Server\ApplicationRequestHandler;
use Nette\Neon\Neon;

$configPath = 'config.neon';
$fileContent = loadFile($configPath);
if (null === $fileContent) {
    $fileContent = loadFile('../'. $configPath);
}
$config = Neon::decode($fileContent);
$server = new Server(new ApplicationRequestHandler($config['hosts'], new MemoryStream()));
$server->listen(9900);

Loop\run();

Load config file from root in /src or /

Load config file from root in /src or /


<?php namespace Worldpay;

class Translate {

  /**
   * Set Test Mode
   *
   * Convert WorldPay environment from string to integer
   *
   * @var $input string
   * @return integer
   */
  public static function setTestMode($input)
  {
    if($input == 'production'){return 0;}

    return 100;
  }

  /**
   * Get Test Mode
   *
   * Convert WorldPay environment from integer to string
   *
   * @var $input integer
   * @return string
   */
  public static function getTestMode($input)
  {
    if($input == 0){return 'production';}

    return 'development';
  }

  public static function unit($input)
  {
    $units = array('day' => 1, 'week' => 2, 'month' => 3, 'year' => 4);

    return $units[rtrim($input, 's')];
  }

}

<?php namespace Worldpay;

class Translate {

  /**
   * Set Test Mode
   *
   * Convert WorldPay environment from string to integer
   *
   * @var $input string
   * @return integer
   */
  public static function setTestMode($input)
  {
    if($input == 'production'){return 0;}

    return 100;
  }

  /**
   * Get Test Mode
   *
   * Convert WorldPay environment from integer to string
   *
   * @var $input integer
   * @return string
   */
  public static function getTestMode($input)
  {
    if($input == 0){return 'production';}

    return 'development';
  }

  /**
   * Unit
   *
   * Convert interval string into correct WorldPay parameter
   *
   * @var $input string
   * @return integer
   */
  public static function unit($input)
  {
    $units = array('day' => 1, 'week' => 2, 'month' => 3, 'year' => 4);

    return $units[rtrim($input, 's')];
  }

}

Add comment block to unit helper method

Add comment block to unit helper method


<?php

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

namespace Surfnet\ServiceProviderDashboard\Infrastructure\DashboardBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

class Builder implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');

        $menu->addChild('Services', array('route' => 'entity_list'));

        $menu->addChild('Add new supplier', array(
            'route' => 'supplier_add',
        ));
        $menu->addChild('Edit supplier', array(
            'route' => 'supplier_edit',
        ));

        return $menu;
    }
}

<?php

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

namespace Surfnet\ServiceProviderDashboard\Infrastructure\DashboardBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

class Builder implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');

        $menu->addChild('Services', array('route' => 'entity_list'));

        $menu->addChild('Add new service', array(
            'route' => 'service_add',
        ));
        $menu->addChild('Add new supplier', array(
            'route' => 'supplier_add',
        ));
        $menu->addChild('Edit supplier', array(
            'route' => 'supplier_edit',
        ));

        return $menu;
    }
}

Add the CreateServiceCommand to the Menu


<?php

class ExampleCPT extends LRCPT{

    public $name;
    public $labels = array('name' => 'Blaa');

    public $args = array();

    public $metaboxes = array();

    /**
    * Call the parent constuctor to do all the work.
    */
    public function __construct(){
        $this->metaboxes[] = array(
            'id'       => 'blaa',
            'title'    => 'blaa',
            'pages'    => 'blaa',
            'fields'   => array(
                array(
                    'id' => 'sometext',
                    'name' => 'Some text',
                    'type' => 'text',
                    'cols' => 3
                ),
            )
        );

        PARENT::__construct();
    }
}

<?php

use laserred\lrcpt;

class ExampleCPT extends lrcpt{

    public $name;
    public $labels = array('name' => 'Blaa');

    public $args = array();

    public $metaboxes = array();

    /**
    * Call the parent constuctor to do all the work.
    */
    public function __construct(){
        $this->metaboxes[] = array(
            'id'       => 'blaa',
            'title'    => 'blaa',
            'pages'    => 'blaa',
            'fields'   => array(
                array(
                    'id' => 'sometext',
                    'name' => 'Some text',
                    'type' => 'text',
                    'cols' => 3
                ),
            )
        );

        PARENT::__construct();
    }
}

Use proper PSR4 in example

Use proper PSR4 in example


<?php

use Galahad\LaravelAddressing\Country;
use Galahad\LaravelAddressing\Locality;

/**
 * Class LocalityTest
 *
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class LocalityTest extends PHPUnit_Framework_TestCase
{
    public function testBeloHorizonteCity()
    {
        $brazil = (new Country)->getByCode('BR');
        $states = $brazil->getAdministrativeAreas();
        $minasGerais = $states->getByCode('MG');
        $beloHorizonte = $minasGerais->getLocalities()->getByName('Belo Horizonte');

        $this->assertEquals($beloHorizonte->getAdministrativeArea()->getName(), 'Minas Gerais');
        $this->assertEquals($beloHorizonte->getName(), 'Belo Horizonte');
        $this->assertInstanceOf(Locality::class, $beloHorizonte);
    }

//    public function testBoulderCity()
//    {
//        $colorado = (new Country)->getByCode('US')->getAdministrativeAreas()->getByName('Colorado');
//
//        $this->assertEquals($colorado->getLocalities()->getByName('Boulder'), 'Boulder');
//    }
}

<?php

use Galahad\LaravelAddressing\Country;
use Galahad\LaravelAddressing\LaravelAddressing;
use Galahad\LaravelAddressing\Locality;

/**
 * Class LocalityTest
 *
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class LocalityTest extends PHPUnit_Framework_TestCase
{
    public function testBeloHorizonteCity()
    {
        $brazil = (new Country)->getByCode('BR');
        $states = $brazil->getAdministrativeAreas();
        $minasGerais = $states->getByCode('MG');
        $beloHorizonte = $minasGerais->getLocalities()->getByName('Belo Horizonte');

        $this->assertEquals($beloHorizonte->getAdministrativeArea()->getName(), 'Minas Gerais');
        $this->assertEquals($beloHorizonte->getName(), 'Belo Horizonte');
        $this->assertInstanceOf(Locality::class, $beloHorizonte);
    }

    public function testGetMagicMethod()
    {
        $maker = new LaravelAddressing();
        $city = $maker->country('BR')->state('MG')->city('Belo Horizonte');

        $this->assertEquals($city->name, 'Belo Horizonte');
    }

//    public function testBoulderCity()
//    {
//        $colorado = (new Country)->getByCode('US')->getAdministrativeAreas()->getByName('Colorado');
//
//        $this->assertEquals($colorado->getLocalities()->getByName('Boulder'), 'Boulder');
//    }
}

Add test for __get magic method in Locality class


<?php
set_include_path(dirname(__FILE__) . '/../' . PATH_SEPARATOR . get_include_path());

require_once 'Slim/Slim.php';

// Register Slim's autoloader
\Slim\Slim::registerAutoloader();

//Register non-Slim autoloader
function customAutoLoader( $class )
{
    $file = rtrim(dirname(__FILE__), '/') . '/' . $class . '.php';
    if ( file_exists($file) ) {
        require $file;
    } else {
        return;
    }
}
spl_autoload_register('customAutoLoader');

<?php
set_include_path(dirname(__FILE__) . '/../' . PATH_SEPARATOR . get_include_path());

// Set default timezone
date_default_timezone_set('America/New_York');

require_once 'Slim/Slim.php';

// Register Slim's autoloader
\Slim\Slim::registerAutoloader();

//Register non-Slim autoloader
function customAutoLoader( $class )
{
    $file = rtrim(dirname(__FILE__), '/') . '/' . $class . '.php';
    if ( file_exists($file) ) {
        require $file;
    } else {
        return;
    }
}
spl_autoload_register('customAutoLoader');

Set default timezone for unit tests

Set default timezone for unit tests


<?php
namespace Neos\Flow\Tests\Functional\Reflection\Fixtures\Model;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

/**
 * A model fixture which is used for testing the class schema building
 *
 * @Flow\Entity
 */
class SuperEntity extends AbstractSuperEntity
{
    /**
     * Just a normal string
     *
     * @var string
     */
    protected $someString;

    /**
     * Just a string that can be null
     *
     * @var string|null
     */
    protected $someNullableString;

    /**
     * Just an int that can be null
     *
     * @var null|int
     */
    protected $someNullableInt;

    /**
     * Just an array of strings that can be null
     *
     * @var array<string>|null
     */
    protected $someNullableArrayOfStrings;
}

<?php
namespace Neos\Flow\Tests\Functional\Reflection\Fixtures\Model;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

/**
 * A model fixture which is used for testing the class schema building
 *
 * @Flow\Entity
 */
class SuperEntity extends AbstractSuperEntity
{
    /**
     * Just a normal string
     *
     * @var string
     */
    protected $someString;

    /**
     * Just a string that can be null
     *
     * @var string|null
     */
    protected $someNullableString;

    /**
     * Just an int that can be null
     *
     * @var null|int
     */
    protected $someNullableInt;

    /**
     * Just an array of strings that can be null
     *
     * @var array<string>|null
     */
    protected $someNullableArrayOfStrings;

    /**
     * A nullable property with a fully qualified class name
     *
     * @var \DateTimeInterface|null
     */
    protected $aNullableDateTime;
}

TASK: Add test fixture for nullable fully qualified class property


<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'mail@roadgenius.de'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@roadgenius.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "Bitte alle Felder ausfüllen!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'mail@roadgenius.de'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Roadgenius - Nachricht von $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@roadgenius.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Change success message text-language to german


<?php

namespace Mini\Model\TypeCrawler;

use \Mini\Model\TypeCrawler\Storage\StorageFactory;

class TypeCrawlerController {
    /** @var array */
    private $crawlers;
    /** @var StorageFactory */
    private $storage;

    function __construct(StorageFactory $storageFactory) {
        $this->crawlers = array();
        $this->storage = $storageFactory;

        $this->registerCrawler('ModBot');
    }

    public function registerCrawler(string $crawler) {
        $this->crawlers[] = new $crawler($this->storage->getStorage($crawler::$type));
    }

    public function triggerCrawl(): array {
        $ret = array();
        foreach($this->crawlers as $crawler) {
            $ret = array_merge($ret, $crawler->crawl());
        }
    }
}

<?php

namespace Mini\Model\TypeCrawler;

use \Mini\Model\TypeCrawler\Storage\StorageFactory;
//TODO do this right
use \Mini\Model\TypeCrawler\ModBot;

class TypeCrawlerController {
    /** @var array */
    private $crawlers;
    /** @var StorageFactory */
    private $storage;

    function __construct(StorageFactory $storageFactory) {
        $this->crawlers = array();
        $this->storage = $storageFactory;

        $this->registerCrawler('ModBot');
    }

    public function registerCrawler(string $crawler) {
        $this->crawlers[] = new $crawler($this->storage->getStorage($crawler::$type));
    }

    public function triggerCrawl(): array {
        $ret = array();
        foreach($this->crawlers as $crawler) {
            $ret = array_merge($ret, $crawler->crawl());
        }
    }
}

Make the thing work, for now

Make the thing work, for now


<?php

namespace Uploadify;

use Illuminate\Contracts\Filesystem\Factory as Storage;
use Illuminate\Http\UploadedFile;
use Intervention\Image\Image as InterventionImage;
use Illuminate\Database\Eloquent\Model as Eloquent;

class UploadifyManager
{
    /**
     * The filesystem factory instance
     *
     * @var \Illuminate\Contracts\Filesystem\Factory
     */
    protected $storage;

    /**
     * The list of settings
     *
     * @var array
     */
    protected $settings = [];

    /**
     * Create new uploadify instance
     *
     * @param  \Illuminate\Contracts\Filesystem\Factory  $storage
     * @param  array  $settings
     * @return void
     */
    public function __construct(Storage $storage, array $settings = [])
    {
        $this->storage = $storage;
        $this->settings = $settings;
    }

    /**
     * Create new uploadify instance
     *
     * @param  \Illuminate\Http\UploadedFile  $file
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  \Uploadify\Uploadify  $field
     * @return self
     */
    public function create(UploadedFile $file, Eloquent $model, $field)
    {

    }
}

<?php

namespace Uploadify;

use Illuminate\Contracts\Filesystem\Factory as Storage;
use Illuminate\Http\UploadedFile;
use Intervention\Image\Image as InterventionImage;
use Illuminate\Database\Eloquent\Model as Eloquent;

class UploadifyManager
{
    /**
     * The filesystem factory instance
     *
     * @var \Illuminate\Contracts\Filesystem\Factory
     */
    protected $storage;

    /**
     * The list of settings
     *
     * @var array
     */
    protected $settings = [];

    /**
     * Create new uploadify instance
     *
     * @param  \Illuminate\Contracts\Filesystem\Factory  $storage
     * @param  array  $settings
     * @return void
     */
    public function __construct(Storage $storage, array $settings = [])
    {
        $this->storage = $storage;
        $this->settings = $settings;
    }

    /**
     * Create new uploadify instance
     *
     * @param  \Illuminate\Http\UploadedFile  $file
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  \Uploadify\Uploadify  $field
     * @return self
     */
    public function create(UploadedFile $file, Eloquent $model, $field)
    {
        return;
    }
}

Test return in create() method

Test return in create() method


<?php

namespace CottaCush\Yii2\Assets;

/**
 * Class ToastrAsset
 * Asset for Toastr.js
 * @author Olajide Oye <jide@cottacush.com>
 * @package CottaCush\Yii2\Assets
 */
class ToastrAsset extends AssetBundle
{
    public $sourcePath = '@npm/toastr';
    public $css = [
        'toastr.min.css'
    ];
    public $js = [
        'toastr.min.js'
    ];
    public $productionCss = [
        'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.3/toastr.min.css'
    ];
    public $productionJs = [
        'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.3/toastr.min.js'
    ];
    public $depends = [
        'yii\web\JqueryAsset'
    ];
}

<?php

namespace CottaCush\Yii2\Assets;

/**
 * Class ToastrAsset
 * Asset for Toastr.js
 * @author Olajide Oye <jide@cottacush.com>
 * @package CottaCush\Yii2\Assets
 */
class ToastrAsset extends AssetBundle
{
    public $sourcePath = '@npm/toastr/build';
    public $css = [
        'toastr.min.css'
    ];
    public $js = [
        'toastr.min.js'
    ];
    public $productionCss = [
        'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.3/toastr.min.css'
    ];
    public $productionJs = [
        'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.3/toastr.min.js'
    ];
    public $depends = [
        'yii\web\JqueryAsset'
    ];
}

Fix toastr npm asset path

Fix toastr npm asset path


<?php namespace Cerbero\Workflow;

/**
 * Interface for classes that run workflow.
 *
 * @author	Andrea Marco Sartori
 */
interface WorkflowRunnerInterface {

	/**
	 * Set the workflows to run.
	 *
	 * @author	Andrea Marco Sartori
	 * @param	Cerbero\Workflow\Workflow	$workflow
	 * @return	void
	 */
	public function setWorkflow(Workflow $workflow);

}

<?php namespace Cerbero\Workflow;

/**
 * Interface for classes that run workflow.
 *
 * @author	Andrea Marco Sartori
 */
interface WorkflowRunner {

	/**
	 * Set the workflows to run.
	 *
	 * @author	Andrea Marco Sartori
	 * @param	Cerbero\Workflow\Workflow	$workflow
	 * @return	void
	 */
	public function setWorkflow(Workflow $workflow);

}

Rename the interface for workflow runners


<?php
require_once('Autoload.php');

class TicketSystemSettings extends Singleton
{
    protected $cache;
    protected $datatable;

    protected function __construct()
    {
        $this->cache = array();
        $dataset = DataSetFactory::get_data_set('tickets');
        $this->datatable = $dataset['Variables'];
    }

    public function getVariable($var_name, $default=false)
    {
        if(isset($this->cache[$var_name]))
        {
            return $this->cache[$var_name];
        }
        $vars = $this->datatable->read(new \Data\Filter("name eq '$var_name'"));
        if($vars === false || !isset($vars))
        {
            return $default;
        }
        $this->cache[$var_name] = $vars[0]['value'];
        return $this->cache[$var_name];
    }

    public function setVariable($var_name, $value)
    {
        $this->cache[$var_name] = $value;
        return $this->datatable->update(new \Data\Filter("name eq '$var_name'"), array('value'=>$value));
    }

    public function isTestMode()
    {
        return $this->getVariable('test_mode') === '1';
    }
}
?>

<?php
require_once('Autoload.php');

class TicketSystemSettings extends Singleton
{
    protected $cache;
    protected $datatable;

    protected function __construct()
    {
        $this->cache = array();
        $dataset = DataSetFactory::get_data_set('tickets');
        $this->datatable = $dataset['Variables'];
    }

    public function getVariable($var_name, $default=false)
    {
        if(isset($this->cache[$var_name]))
        {
            return $this->cache[$var_name];
        }
        $vars = $this->datatable->read(new \Data\Filter("name eq '$var_name'"));
        if($vars === false || !isset($vars))
        {
            return $default;
        }
        $this->cache[$var_name] = $vars[0]['value'];
        return $this->cache[$var_name];
    }

    public function setVariable($var_name, $value)
    {
        $this->cache[$var_name] = $value;
        return $this->datatable->update(new \Data\Filter("name eq '$var_name'"), array('value'=>$value));
    }

    public function createVariable($var_name, $value)
    {
        $this->cache[$var_name] = $value;
        return $this->datatable->create(array('name'=>$var_name, 'value'=>$value));
    }

    public function deleteVariable($var_name)
    {
        unset($this->cache[$var_name]);
        return $this->datatable->delete(new \Data\Filter("name eq '$var_name'"));
    }

    public function isTestMode()
    {
        return $this->getVariable('test_mode') === '1';
    }

    public function toArray()
    {
        $vars = $this->datatable->read();
        $count = count($vars);
        for($i = 0; $i < $count; $i++)
        {
            $this->cache[$vars[$i]['name']] = $vars[$i]['value'];
        }
        return $this->cache;
    }
}
?>

Add support for creating and deleting variables


		Version <?php echo $app_version; ?>

	Copyright © 2016 Bitcraft Labs. All rights reserved.

Change version link to the project homepage


<?php

namespace Wanjee\Shuwee\AdminBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Wanjee\Shuwee\AdminBundle\Event\ConfigureMenuEvent;

/**
 * Class Builder
 * @package Wanjee\Shuwee\AdminBundle\Menu
 */
class Builder
{
    /**
     * @var \Knp\Menu\FactoryInterface
     */
    private $factory;

    /**
     * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
     */
    private $dispatcher;

    /**
     * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
     * @param \Knp\Menu\FactoryInterface $factory
     */
    public function __construct(FactoryInterface $factory, EventDispatcherInterface $dispatcher)
    {
        $this->factory = $factory;
        $this->dispatcher = $dispatcher;
    }

    /**
     * Build main menu.
     *
     * Let any bundle add items to this menu by subscribing to ConfigureMenuEvent::CONFIGURE
     * @see ConfigureMenuContentListener for example
     *
     * @param array $options
     * @return \Knp\Menu\ItemInterface
     */
    public function sideMenu(array $options)
    {
        $menu = $this->factory->createItem('root');

        $this->dispatcher->dispatch(
            ConfigureMenuEvent::CONFIGURE,
            new ConfigureMenuEvent($this->factory, $menu)
        );

        return $menu;
    }
}

<?php

namespace Wanjee\Shuwee\AdminBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Wanjee\Shuwee\AdminBundle\Event\ConfigureMenuEvent;

/**
 * Class Builder
 * @package Wanjee\Shuwee\AdminBundle\Menu
 */
class Builder
{
    /**
     * @var \Knp\Menu\FactoryInterface
     */
    private $factory;

    /**
     * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
     */
    private $dispatcher;

    /**
     * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
     * @param \Knp\Menu\FactoryInterface $factory
     */
    public function __construct(FactoryInterface $factory, EventDispatcherInterface $dispatcher)
    {
        $this->factory = $factory;
        $this->dispatcher = $dispatcher;
    }

    /**
     * Build main menu.
     *
     * Let any bundle add items to this menu by subscribing to ConfigureMenuEvent::CONFIGURE
     * @see ConfigureMenuContentListener for example
     *
     * @param array $options
     * @return \Knp\Menu\ItemInterface
     */
    public function sideMenu()
    {
        $menu = $this->factory->createItem('root');

        $this->dispatcher->dispatch(
            ConfigureMenuEvent::CONFIGURE,
            new ConfigureMenuEvent($this->factory, $menu)
        );

        return $menu;
    }
}

Fix "Unused method, property, variable or parameter "


<?php

namespace Edge\QA;

class ConfigTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadDefaultConfig()
    {
        $config = new Config();
        assertThat($config->value('phpcpd.minLines'), is(greaterThan(0)));
        assertThat($config->value('phpcpd.minTokens'), is(greaterThan(0)));
        assertThat($config->value('phpcs.standard'), is(nonEmptyString()));
        assertThat($config->path('phpmd.standard'), is(nonEmptyString()));
    }

    public function testBuildAbsolutePath()
    {
        $config = new Config();
        assertThat($config->path('phpmd.standard'), not(startsWith('app/')));
    }

    public function testOverrideDefaultConfig()
    {
        $config = new Config();
        $config->loadCustomConfig(__DIR__);
        assertThat($config->value('phpcpd.minLines'), is(5));
        assertThat($config->value('phpcpd.minTokens'), is(70));
        assertThat($config->value('phpcs.standard'), is('Zend'));
        assertThat($config->path('phpmd.standard'), is(__DIR__ . "/my-standard.xml"));
    }

    public function testIgnoreNonExistenConfig()
    {
        $directoryWithoutConfig = __DIR__ . '/../';
        $config = new Config();
        $config->loadCustomConfig($directoryWithoutConfig);
        assertThat($config->value('phpcs.standard'), is(nonEmptyString()));
    }

    public function testThrowExceptionWhenFileDoesNotExist()
    {
        $config = new Config();
        $config->loadCustomConfig(__DIR__);
        $this->setExpectedException(\Exception::class);
        $config->path('phpcs.standard');
    }
}

<?php

namespace Edge\QA;

class ConfigTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadDefaultConfig()
    {
        $config = new Config();
        assertThat($config->value('phpcpd.minLines'), is(greaterThan(0)));
        assertThat($config->value('phpcpd.minTokens'), is(greaterThan(0)));
        assertThat($config->value('phpcs.standard'), is(nonEmptyString()));
        assertThat($config->path('phpmd.standard'), is(nonEmptyString()));
    }

    public function testBuildAbsolutePath()
    {
        $config = new Config();
        assertThat($config->path('phpmd.standard'), not(startsWith('app/')));
    }

    public function testOverrideDefaultConfig()
    {
        $config = new Config();
        $config->loadCustomConfig(__DIR__);
        assertThat($config->value('phpcpd.minLines'), is(5));
        assertThat($config->value('phpcpd.minTokens'), is(70));
        assertThat($config->value('phpcs.standard'), is('Zend'));
        assertThat($config->path('phpmd.standard'), is(__DIR__ . "/my-standard.xml"));
    }

    public function testIgnoreNonExistenConfig()
    {
        $directoryWithoutConfig = __DIR__ . '/../';
        $config = new Config();
        $config->loadCustomConfig($directoryWithoutConfig);
        assertThat($config->value('phpcs.standard'), is(nonEmptyString()));
    }

    public function testThrowExceptionWhenFileDoesNotExist()
    {
        $config = new Config();
        $config->loadCustomConfig(__DIR__);
        $this->setExpectedException('Exception');
        $config->path('phpcs.standard');
    }
}

Fix testing expected exception in php 5.4


<?php

final class HarbormasterBuildPlanDatasource
  extends PhabricatorTypeaheadDatasource {

  public function getPlaceholderText() {
    return pht('Type a build plan name...');
  }

  public function getDatasourceApplicationClass() {
    return 'PhabricatorHarbormasterApplication';
  }

  public function loadResults() {
    $viewer = $this->getViewer();
    $raw_query = $this->getRawQuery();

    $results = array();

    $plans = id(new HarbormasterBuildPlanQuery())
      ->setViewer($viewer)
      ->execute();
    foreach ($plans as $plan) {
      $results[] = id(new PhabricatorTypeaheadResult())
        ->setName($plan->getName())
        ->setPHID($plan->getPHID());
    }

    return $results;
  }

}

<?php

final class HarbormasterBuildPlanDatasource
  extends PhabricatorTypeaheadDatasource {

  public function getPlaceholderText() {
    return pht('Type a build plan name...');
  }

  public function getDatasourceApplicationClass() {
    return 'PhabricatorHarbormasterApplication';
  }

  public function loadResults() {
    $viewer = $this->getViewer();
    $raw_query = $this->getRawQuery();

    $results = array();

    $plans = id(new HarbormasterBuildPlanQuery())
      ->setViewer($viewer)
      ->execute();
    foreach ($plans as $plan) {
      $closed = null;
      if ($plan->isDisabled()) {
        $closed = pht('Disabled');
      }

      $results[] = id(new PhabricatorTypeaheadResult())
        ->setName($plan->getName())
        ->setClosed($closed)
        ->setPHID($plan->getPHID());
    }

    return $results;
  }

}

Fix buildplan ac on Herald.

T7646: Fix buildplan ac on Herald.

Summary: Fixes T7646.

Test Plan: Repeat steps described in T7646 and expect disabled build plans not displayed.

Reviewers: epriestley, #blessed_reviewers

Reviewed By: epriestley, #blessed_reviewers

Subscribers: Korvin, epriestley

Maniphest Tasks: T7646

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


<?php
namespace Nueve\ViewPresenter;

/**
 * PhpParser
 */
class PhpParser implements ParserInterface
{
    private $templateDirectory;
    private $fileExt = '.php';

    public function __construct($templateDirectory)
    {
        $this->templateDirectory = rtrim($templateDirectory, DIRECTORY_SEPARATOR);
    }

	private function getTemplatePathname($template)
    {
        if (strpos($template, $this->fileExt) !== false) {
            $template = $template . $this->fileExt;
        }

        return $this->templateDirectory . DIRECTORY_SEPARATOR .
            ltrim($template, DIRECTORY_SEPARATOR);
    }

	public function render($template, array $data = [])
	{
		$templateFile = $this->getTemplatePathname($template);

		extract($data);
		ob_start();
		require $templateFile;
		return ob_get_clean();
	}
}

<?php
namespace Nueve\ViewPresenter;

/**
 * PhpParser
 */
class PhpParser implements ParserInterface
{
    private $templateDirectory;
    private $fileExt = '.php';

    public function __construct($templateDirectory)
    {
        $this->templateDirectory = rtrim($templateDirectory, DIRECTORY_SEPARATOR);
    }

	private function getTemplatePathname($template)
    {
        if (strpos($template, $this->fileExt) === false) {
            $template = $template . $this->fileExt;
        }

        return $this->templateDirectory . DIRECTORY_SEPARATOR .
            ltrim($template, DIRECTORY_SEPARATOR);
    }

	public function render($template, array $data = [])
	{
		$templateFile = $this->getTemplatePathname($template);

		extract($data);
		ob_start();
		require $templateFile;
		return ob_get_clean();
	}
}

Update PHP parser to add file extension

Update PHP parser to add file extension


<?php p($l->t('File Sharing'));?>

	<input type="checkbox" name="outgoing_server2server_share_enabled" id="outgoingServer2serverShareEnabled"
		   value="1" <?php if ($_['outgoingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
	<?php p($l->t('Allow other instances to mount public links shared from this server'));?>

	<input type="checkbox" name="incoming_server2server_share_enabled" id="incomingServer2serverShareEnabled"
		   value="1" <?php if ($_['incomingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
	<?php p($l->t('Allow users to mount public link shares'));?>

<?php p($l->t('Remote Shares'));?>

	<input type="checkbox" name="outgoing_server2server_share_enabled" id="outgoingServer2serverShareEnabled"
		   value="1" <?php if ($_['outgoingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
	<?php p($l->t('Allow other instances to mount public links shared from this server'));?>

	<input type="checkbox" name="incoming_server2server_share_enabled" id="incomingServer2serverShareEnabled"
		   value="1" <?php if ($_['incomingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
	<?php p($l->t('Allow users to mount public link shares'));?>

Fix wording for remote shares in settings page


<?php namespace Maatwebsite\Usher\Traits;

use Doctrine\ORM\Mapping as ORM;
use Maatwebsite\Usher\Domain\Shared\Embeddables\CreatedAt;
use Maatwebsite\Usher\Domain\Shared\Embeddables\UpdatedAt;

trait Timestamps
{

    /**
     * @ORM\Embedded(class = "Maatwebsite\Usher\Domain\Shared\Embeddables\CreatedAt", columnPrefix=false)
     * @var CreatedAt
     */
    private $createdAt;

    /**
     * @ORM\Embedded(class = "Maatwebsite\Usher\Domain\Shared\Embeddables\UpdatedAt", columnPrefix=false)
     * @var UpdatedAt
     */
    private $updatedAt;

    /**
     * @ORM\PrePersist
     */
    public function prePersist()
    {
        $this->setCreatedAt(
            new CreatedAt
        );

        $this->setUpdatedAt(
            new UpdatedAt
        );
    }

    /**
     * @ORM\PreUpdate
     */
    public function preUpdate()
    {
        $this->setUpdatedAt(
            new UpdatedAt
        );
    }

    /**
     * @return CreatedAt
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param CreatedAt $createdAt
     */
    public function setCreatedAt(CreatedAt $createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * @return UpdatedAt
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @param UpdatedAt $updatedAt
     */
    public function setUpdatedAt(UpdatedAt $updatedAt)
    {
        $this->updatedAt = $updatedAt;
    }
}

<?php namespace Maatwebsite\Usher\Traits;

use Doctrine\ORM\Mapping as ORM;
use Maatwebsite\Usher\Domain\Shared\Embeddables\CreatedAt;
use Maatwebsite\Usher\Domain\Shared\Embeddables\UpdatedAt;

trait Timestamps
{

    /**
     * @ORM\Embedded(class = "Maatwebsite\Usher\Domain\Shared\Embeddables\CreatedAt", columnPrefix=false)
     * @var CreatedAt
     */
    protected $createdAt;

    /**
     * @ORM\Embedded(class = "Maatwebsite\Usher\Domain\Shared\Embeddables\UpdatedAt", columnPrefix=false)
     * @var UpdatedAt
     */
    protected $updatedAt;

    /**
     * @ORM\PrePersist
     */
    public function prePersist()
    {
        $this->setCreatedAt(
            new CreatedAt
        );

        $this->setUpdatedAt(
            new UpdatedAt
        );
    }

    /**
     * @ORM\PreUpdate
     */
    public function preUpdate()
    {
        $this->setUpdatedAt(
            new UpdatedAt
        );
    }

    /**
     * @return CreatedAt
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param CreatedAt $createdAt
     */
    public function setCreatedAt(CreatedAt $createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * @return UpdatedAt
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @param UpdatedAt $updatedAt
     */
    public function setUpdatedAt(UpdatedAt $updatedAt)
    {
        $this->updatedAt = $updatedAt;
    }
}

Change timestamps columns to protected

Change timestamps columns to protected


<?php

class Tasks extends MY_Model {

    public function __construct() {
        parent::__construct('tasks', 'id');
    }
}

<?php

class Tasks extends MY_Model {

    public function __construct() {
        parent::__construct('tasks', 'id');
    }
    /* in progress
    // provide form validation rules
    public function rules()
    {
        $config = array(
            ['field' => 'task', 'label' => 'TODO task', 'rules' => 'alpha_dash|max_length[64]'],
            ['field' => 'priority', 'label' => 'Priority', 'rules' => 'integer|less_than[4]'],
            ['field' => 'size', 'label' => 'Task size', 'rules' => 'integer|less_than[4]'],
            ['field' => 'group', 'label' => 'Task group', 'rules' => 'integer|less_than[5]'],
        );
        return $config;
    }

    // Initiate adding a new task
    public function add()
    {
        $task = $this->tasks->create();
        $this->session->set_userdata('task', $task);
        $this->showit();
    }
     */
}

Add item maintenance in progess

Add item maintenance in progess


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Mvc\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Resolver as ViewResolver;

class ViewResolverFactory implements FactoryInterface
{
    /**
     * Create the aggregate view resolver
     *
     * Creates a Zend\View\Resolver\AggregateResolver and attaches the template
     * map resolver and path stack resolver
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return ViewResolver\AggregateResolver
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $resolver = new ViewResolver\AggregateResolver();
<<<<<<< HEAD
        $mapResolver = $serviceLocator->get('ViewTemplateMapResolver');
        $pathResolver = $serviceLocator->get('ViewTemplatePathStack');
        $resolver->attach($mapResolver)
                 ->attach($pathResolver)
                 ->attach(new ViewResolver\RelativeFallbackResolver($mapResolver))
                 ->attach(new ViewResolver\RelativeFallbackResolver($pathResolver))
        ;
=======
        $resolver->attach($serviceLocator->get('ViewPrefixPathStackResolver'));
        $resolver->attach($serviceLocator->get('ViewTemplateMapResolver'));
        $resolver->attach($serviceLocator->get('ViewTemplatePathStack'));
>>>>>>> Create PrefixPathStackResolver
        return $resolver;
    }
}

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Mvc\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Resolver as ViewResolver;

class ViewResolverFactory implements FactoryInterface
{
    /**
     * Create the aggregate view resolver
     *
     * Creates a Zend\View\Resolver\AggregateResolver and attaches the template
     * map resolver and path stack resolver
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return ViewResolver\AggregateResolver
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $resolver = new ViewResolver\AggregateResolver();

        $mapResolver = $serviceLocator->get('ViewTemplateMapResolver');
        $pathResolver = $serviceLocator->get('ViewTemplatePathStack');
        $prefixPathStackResolver = $serviceLocator->get('ViewPrefixPathStackResolver');

        $resolver
            ->attach($mapResolver)
            ->attach($pathResolver)
            ->attach($prefixPathStackResolver)
            ->attach(new ViewResolver\RelativeFallbackResolver($mapResolver))
            ->attach(new ViewResolver\RelativeFallbackResolver($pathResolver))
            ->attach(new ViewResolver\RelativeFallbackResolver($prefixPathStackResolver));

        return $resolver;
    }
}

Attach prefix path resolver at end of chain of aggregate resolver


<?php

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$file = basename($path);

if (false !== strpos($file, '.')) {
    return false;
}

$content = @file_get_contents(__DIR__ . '/../../web/' . $path . '.html');

if (false === $content) {
    return false;
}

echo $content;

<?php

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$file = basename($path);

if (false !== strpos($file, '.')) {
    return false;
}

$content = @file_get_contents($_SERVER['DOCUMENT_ROOT'] . $path . '.html');

if (false === $content) {
    return false;
}

echo $content;

Allow other docroots in documentation router


<?php

class Actionlog extends Eloquent
{
	use SoftDeletingTrait;
    protected $dates = ['deleted_at'];

    protected $table = 'asset_logs';
    public $timestamps = false;

    public function assetlog()
    {
        return $this->belongsTo('Asset','asset_id')->withTrashed();
    }

    public function licenselog()
    {
        return $this->belongsTo('License','asset_id');
    }

    public function adminlog()
    {
        return $this->belongsTo('User','user_id');
    }

    public function userlog()
    {
        return $this->belongsTo('User','checkedout_to')->withTrashed();
    }

    /**
    * Get the parent category name
    */
    public function logaction($actiontype)
    {
        $this->action_type = $actiontype;

        if($this->save()) {
            return true;
        } else {
            return false;
        }
    }
}

<?php

class Actionlog extends Eloquent
{

    protected $table = 'asset_logs';
    public $timestamps = false;

    public function assetlog()
    {
        return $this->belongsTo('Asset','asset_id')->withTrashed();
    }

    public function licenselog()
    {
        return $this->belongsTo('License','asset_id');
    }

    public function adminlog()
    {
        return $this->belongsTo('User','user_id');
    }

    public function userlog()
    {
        return $this->belongsTo('User','checkedout_to')->withTrashed();
    }

    /**
    * Get the parent category name
    */
    public function logaction($actiontype)
    {
        $this->action_type = $actiontype;

        if($this->save()) {
            return true;
        } else {
            return false;
        }
    }
}

Fix for asset log incorrectly using soft deletes


<?php

$include_path = ini_get('include_path');
ini_set('include_path', $include_path.':'.dirname(__FILE__).'/../../');
@require_once 'libphutil/src/__phutil_library_init__.php';
if (!@constant('__LIBPHUTIL__')) {
  echo "ERROR: Unable to load libphutil. Update your PHP 'include_path' to ".
       "include the parent directory of libphutil/.\n";
  exit(1);
}

require_once 'libphutil/scripts/__init_script__.php';

if (!ini_get('date.timezone')) {
  date_default_timezone_set('America/Los_Angeles');
}

phutil_load_library(dirname(__FILE__).'/../src/');

<?php

$include_path = ini_get('include_path');
$include_path .= PATH_SEPARATOR.dirname(__FILE__).'/../../';
ini_set('include_path', $include_path);
@include_once 'libphutil/src/__phutil_library_init__.php';
if (!@constant('__LIBPHUTIL__')) {
  echo "ERROR: Unable to load libphutil. Update your PHP 'include_path' to ".
       "include the parent directory of libphutil/.\n";
  exit(1);
}

require_once 'libphutil/scripts/__init_script__.php';

if (!ini_get('date.timezone')) {
  date_default_timezone_set('America/Los_Angeles');
}

phutil_load_library(dirname(__FILE__).'/../src/');

Allow running Diviner on Windows

Allow running Diviner on Windows

Summary: Also print error if libphutil is not found.

Test Plan: Ran it on Windows twice.

Reviewers: epriestley

Reviewed By: epriestley

CC: aran, Korvin

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