<?php

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

/**
 * Papi Property Editor class.
 *
 * @package Papi
 */
class Papi_Property_Editor extends Papi_Property {

	/**
	 * Format the value of the property before it's returned to the application.
	 *
	 * @param  mixed  $value
	 * @param  string $slug
	 * @param  int    $post_id
	 *
	 * @return array
	 */
	public function format_value( $value, $slug, $post_id ) {
		return apply_filters( 'the_content', $value );
	}

	/**
	 * Render property html.
	 */
	public function html() {
		$value = $this->get_value();
		$id    = str_replace(
			'[',
			'',
			str_replace( ']', '', $this->html_name() )
		) . '-' . uniqid();

		wp_editor( $value, $id, [
			'textarea_name' => $this->html_name(),
			'media_buttons' => true
		] );

		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			add_filter( 'mce_external_plugins', '__return_empty_array' );
		}
	}
}

<?php

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

/**
 * Papi Property Editor class.
 *
 * @package Papi
 */
class Papi_Property_Editor extends Papi_Property {

	/**
	 * Format the value of the property before it's returned to the application.
	 *
	 * @param  mixed  $value
	 * @param  string $slug
	 * @param  int    $post_id
	 *
	 * @return array
	 */
	public function format_value( $value, $slug, $post_id ) {
		return is_admin() ? $value : apply_filters( 'the_content', $value );
	}

	/**
	 * Render property html.
	 */
	public function html() {
		$value = $this->get_value();
		$id    = str_replace(
			'[',
			'',
			str_replace( ']', '', $this->html_name() )
		) . '-' . uniqid();

		wp_editor( $value, $id, [
			'textarea_name' => $this->html_name(),
			'media_buttons' => true
		] );

		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			add_filter( 'mce_external_plugins', '__return_empty_array' );
		}
	}
}

Fix issue with editor content

Fix issue with editor content


<?php
/**
 * Plugin Name: Set Theme Directory
 */

if (! is_blog_installed()) {
    return;
}

register_theme_directory(dirname(__DIR__) . '/' . env('APP_PUBLIC', 'public') . '/themes');

add_filter('wp_prepare_themes_for_js', function ($themes) {
    foreach ($themes as &$theme) {
        if (! empty($theme['screenshot'])) {
            foreach ($theme['screenshot'] as &$screenshot) {
                $screenshot = str_replace(public_path(), '', $screenshot);
            }
        }
    }

    return $themes;
});

<?php
/**
 * Plugin Name: Set Theme Directory
 */

if (! is_blog_installed()) {
    return;
}

register_theme_directory(public_path('themes'));

add_filter('wp_prepare_themes_for_js', function ($themes) {
    foreach ($themes as &$theme) {
        if (! empty($theme['screenshot'])) {
            foreach ($theme['screenshot'] as &$screenshot) {
                $screenshot = str_replace(public_path(), '', $screenshot);
            }
        }
    }

    return $themes;
});

Use public_path to register theme directory


<?php

namespace Nelmio\SecurityBundle\DependencyInjection\Compiler;

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

class CspReportFilterCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $services = $container->findTaggedServiceIds('nelmio_security.csp_report_filter');

        $cspViolationLogFilterDefinition = $container->getDefinition('nelmio_security.csp_report.filter');

        foreach ($services as $id => $attributes) {
            $cspViolationLogFilterDefinition->addMethodCall('addNoiseDetector', array(new Reference($id)));
        }
    }
}

<?php

namespace Nelmio\SecurityBundle\DependencyInjection\Compiler;

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

class CspReportFilterCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('nelmio_security.csp_report.filter')) {
            return;
        }

        $services = $container->findTaggedServiceIds('nelmio_security.csp_report_filter');

        $cspViolationLogFilterDefinition = $container->getDefinition('nelmio_security.csp_report.filter');

        foreach ($services as $id => $attributes) {
            $cspViolationLogFilterDefinition->addMethodCall('addNoiseDetector', array(new Reference($id)));
        }
    }
}

Abort CSP compiler pass when CSP is not enabled

When csp enabled is set to false in the configuration csp.xml will not be loaded,
so there is no service `nelmio_security.csp_report.filter` and asking the definition
for that non-existing service results in an exception.

So first we check if the service is available in the container and if it's not we bail out
(return early).


<?php

namespace Xtreamwayz\HTMLFormValidator\FormElement;

use DOMElement;
use Zend\InputFilter\InputInterface;
use Zend\Validator;

class Checkbox extends AbstractFormElement
{
    /**
     * @inheritdoc
     */
    protected function attachDefaultValidators(InputInterface $input, DOMElement $element)
    {
    }
}

<?php

namespace Xtreamwayz\HTMLFormValidator\FormElement;

use DOMElement;
use Zend\InputFilter\InputInterface;
use Zend\Validator;

class Checkbox extends AbstractFormElement
{
    /**
     * @inheritdoc
     */
    protected function attachDefaultValidators(InputInterface $input, DOMElement $element)
    {
        // Make sure the submitted value is the same as the original
        if ($element->hasAttribute('checked')) {
            $input->getValidatorChain()
                  ->attach(new Validator\Identical($element->getAttribute('value')));
        }
    }
}

Make sure the submitted checkbox value is the same as the original


<?php
$this->data['header'] = $this->t('{userid:error:header}');

$this->data['head'] = <<<EOF
<meta name="robots" content="noindex, nofollow" />
<meta name="googlebot" content="noarchive, nofollow" />
EOF;

$this->includeAtTemplateBase('includes/header.php');
?>

<?php echo $this->t('{userid:error:title}'); ?>

<?php
echo ('
' . $this->t('{userid:error:descr_' . $this->data['errorCode'] . '}', $this->data['parameters']) . '
');

echo (
    '
data['parameters']['%BASEDIR%'] . 'saml2/idp/initSLO.php?RelayState='
    . urlencode($this->data['parameters']['%RESTARTURL%'])) . '">' . $this->t('{userid:error:retry}') . '
'
);
?>

<?php
$this->includeAtTemplateBase('includes/footer.php');

<?php
$this->data['header'] = $this->t('{userid:error:header}');

$this->data['head'] = <<<EOF
<meta name="robots" content="noindex, nofollow" />
<meta name="googlebot" content="noarchive, nofollow" />
EOF;

$this->includeAtTemplateBase('includes/header.php');
$translationParams = [
    '%IDPNAME%' => $this->data['parameters']['%IDPNAME%'],
];
?>

<?php echo $this->t('{userid:error:title}'); ?>

<?php
echo ('
' . $this->t('{userid:error:descr_' . $this->data['errorCode'] . '}', $translationParams) . '
');

echo (
    '
data['parameters']['%BASEDIR%'] . 'saml2/idp/initSLO.php?RelayState='
    . urlencode($this->data['parameters']['%RESTARTURL%'])) . '">' . $this->t('{userid:error:retry}') . '
'
);
?>

<?php
$this->includeAtTemplateBase('includes/footer.php');

Fix "Array to string conversion" bug related to errorParams


<?php
/**
 * SimpleComplex PHP Config
 * @link      https://github.com/simplecomplex/php-config
 * @copyright Copyright (c) 2017 Jacob Friis Mathiasen
 * @license   https://github.com/simplecomplex/php-config/blob/master/LICENSE (MIT License)
 */
declare(strict_types=1);

namespace SimpleComplex\Config;

/**
 * Convenience class.
 *
 * Consider sub-classing, to make it easier shifting to another
 * SectionedConfigInterface implementation.
 * Then to shift, simply extend another class than this.
 *
 * @dependency-injection-container config
 *      Suggested ID of the Config 'global' instance.
 *
 * @package SimpleComplex\Config
 */
class Config extends IniSectionedConfig
{
    /**
     * @var IniSectionedConfig[]
     */
    protected static $instances = [];

    /**
     * First object instantiated via this method and with that arg name,
     * disregarding class called on.
     *
     * @deprecated Use a dependency injection container instead.
     * @see \SimpleComplex\Utils\Dependency
     * @see \Slim\Container
     *
     * @param string $name
     *      Default: global
     *
     * @return IniSectionedConfig|static
     */
    public static function getInstance($name = 'global')
    {
        return static::$instances[$name] ?? (static::$instances[$name] = new static($name));
    }
}

<?php
/**
 * SimpleComplex PHP Config
 * @link      https://github.com/simplecomplex/php-config
 * @copyright Copyright (c) 2017 Jacob Friis Mathiasen
 * @license   https://github.com/simplecomplex/php-config/blob/master/LICENSE (MIT License)
 */
declare(strict_types=1);

namespace SimpleComplex\Config;

/**
 * Convenience class.
 *
 * Consider sub-classing, to make it easier shifting to another
 * SectionedConfigInterface implementation.
 * Then to shift, simply extend another class than this.
 *
 * @dependency-injection-container config
 *      Suggested ID of the Config 'global' instance.
 *
 * @cache-store config.global
 *      Name of cache store used by this class (effectively).
 *
 * @config-store global
 *      Name of config store used by this class (effectively).
 *
 * @package SimpleComplex\Config
 */
class Config extends IniSectionedConfig
{
    /**
     * @var IniSectionedConfig[]
     */
    protected static $instances = [];

    /**
     * First object instantiated via this method and with that arg name,
     * disregarding class called on.
     *
     * @deprecated Use a dependency injection container instead.
     * @see \SimpleComplex\Utils\Dependency
     * @see \Slim\Container
     *
     * @param string $name
     *      Default: global
     *
     * @return IniSectionedConfig|static
     */
    public static function getInstance($name = 'global')
    {
        return static::$instances[$name] ?? (static::$instances[$name] = new static($name));
    }
}

Document @cache-store and @config-store used.


<?php

namespace GnuCash\Models\Tests;

use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Schema\Blueprint;
use PHPUnit_Framework_TestCase;

abstract class EloquentTestCase extends PHPUnit_Framework_TestCase
{
    protected $connection = 'gnucash_book_test';

    public function setUp()
    {
        $this->configureDatabase();
        $this->migrateTable();
    }

    protected function configureDatabase()
    {
        $db = new DB();
        $db->addConnection([
            'driver'    => 'sqlite',
            'database'  => ':memory:',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ], $this->connection);
        $db->bootEloquent();
        $db->setAsGlobal();
    }

    public function migrateTable()
    {
        $columns = $this->columns();
        DB::schema($this->connection)->create($this->table(), function (Blueprint $table) use ($columns) {
            foreach ($columns as $name => $type) {
                $table->$type($name);
                if (in_array($name, ['id', 'guid'])) {
                    $table->primary($name);
                }
            }
        });
        Eloquent::unguard();
    }

    abstract protected function table();

    abstract protected function columns();
}

<?php

namespace GnuCash\Models\Tests;

use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Schema\Blueprint;
use PHPUnit_Framework_TestCase;

abstract class EloquentTestCase extends PHPUnit_Framework_TestCase
{
    protected $connection = 'gnucash_book_test';

    public function setUp()
    {
        $this->configureDatabase();
        $this->migrateTable();
    }

    protected function configureDatabase()
    {
        $db = new DB();
        $db->addConnection([
            'driver'    => 'sqlite',
            'database'  => ':memory:',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ], $this->connection);
        $db->bootEloquent();
        $db->setAsGlobal();
        Eloquent::unguard();
    }

    public function migrateTable()
    {
        $columns = $this->columns();
        DB::schema($this->connection)->create($this->table(), function (Blueprint $table) use ($columns) {
            foreach ($columns as $name => $type) {
                $table->$type($name);
                if (in_array($name, ['id', 'guid'])) {
                    $table->primary($name);
                }
            }
        });
    }

    abstract protected function table();

    abstract protected function columns();
}

Move to more appropriate place

Move to more appropriate place


<?php

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

namespace Sylius\Bundle\CoreBundle\EventListener;

use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Sylius\Component\Resource\Exception\UnexpectedTypeException;
use Symfony\Component\EventDispatcher\GenericEvent;

/**
 * User update listener.
 *
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
class UserUpdateListener
{
    protected $userManager;

    public function __construct(UserManagerInterface $userManager)
    {
        $this->userManager = $userManager;
    }

    public function processUser(GenericEvent $event)
    {
        $user = $event->getSubject();

        if (!$user instanceof UserInterface) {
            throw new UnexpectedTypeException(
                $user,
                'FOS\UserBundle\Model\UserInterface'
            );
        }

        $this->userManager->reloadUser($user);
    }
}

<?php

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

namespace Sylius\Bundle\CoreBundle\EventListener;

use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Sylius\Component\Resource\Exception\UnexpectedTypeException;
use Symfony\Component\EventDispatcher\GenericEvent;

/**
 * User update listener.
 *
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
class UserUpdateListener
{
    protected $userManager;

    public function __construct(UserManagerInterface $userManager)
    {
        $this->userManager = $userManager;
    }

    public function processUser(GenericEvent $event)
    {
        $user = $event->getSubject();

        if (!$user instanceof UserInterface) {
            throw new UnexpectedTypeException(
                $user,
                'FOS\UserBundle\Model\UserInterface'
            );
        }

        $this->userManager->updateUser($user);
        $this->userManager->reloadUser($user);
    }
}

Fix user password editing in the backend


<?php declare(strict_types=1);
/**
 * @author Janek Ostendorf <janek@ostendorf-vechta.de>
 */

namespace ozzyfant\VersionWarner;

abstract class HttpVersionProvider extends VersionProvider
{

    const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13';

    /**
     * Query an HTTP endpoint and return the result as string
     *
     * @param string $url The URL to query
     * @param string $userAgent The user agent string to use for the query. Defaults to Mozilla/5.0 [...]
     * @return string The HTTP request result
     */
    protected static function queryHttp(string $url, string $userAgent = self::DEFAULT_USER_AGENT): string
    {
        // see https://stackoverflow.com/a/11680776
        // create curl resource
        $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, $url);

        // return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_USERAGENT,$userAgent);

        // $output contains the output string
        $output = curl_exec($ch);

        // close curl resource to free up system resources
        curl_close($ch);

        return $output;
    }

}

<?php declare(strict_types=1);
/**
 * @author Janek Ostendorf <janek@ostendorf-vechta.de>
 */

namespace ozzyfant\VersionWarner;

abstract class HttpVersionProvider extends VersionProvider
{

    const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13';

    /**
     * Query an HTTP endpoint and return the result as string
     *
     * @param string $url The URL to query
     * @param string $userAgent The user agent string to use for the query. Defaults to Mozilla/5.0 [...]
     * @return string The HTTP request result
     */
    protected static function queryHttp(string $url, string $userAgent = self::DEFAULT_USER_AGENT): string
    {
        // see https://stackoverflow.com/a/11680776
        // create curl resource
        $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, $url);

        // return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_USERAGENT, $userAgent);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        // $output contains the output string
        $output = curl_exec($ch);

        if ($output === false) {
            throw new \RuntimeException("Error fetching HTTP response: " . curl_error($ch), curl_errno($ch));
        }

        // close curl resource to free up system resources
        curl_close($ch);

        return $output;
    }

}

Throw error messages if present

cURL: Throw error messages if present


<?php

namespace JeroenNoten\LaravelAdminLte\Menu;

use Illuminate\Contracts\Routing\UrlGenerator;
use Illuminate\Http\Request;

class ActiveChecker
{
    private $request;

    private $url;

    public function __construct(Request $request, UrlGenerator $url)
    {
        $this->request = $request;
        $this->url = $url;
    }

    public function isActive($item)
    {
        if (isset($item['active'])) {
            return $this->isExplicitActive($item['active']);
        }

        if (isset($item['submenu'])) {
            return $this->containsActive($item['submenu']);
        }

        if (isset($item['url'])) {
            return $this->checkExact($item['url']) || $this->checkSub($item['url']);
        }

        return false;
    }

    protected function checkExact($url)
    {
        return $this->checkPattern($url);
    }

    protected function checkSub($url)
    {
        return $this->checkPattern($url.'/*');
    }

    protected function checkPattern($pattern)
    {
        $fullUrlPattern = $this->url->to($pattern);

        return $this->request->fullUrlIs($fullUrlPattern);
    }

    protected function containsActive($items)
    {
        foreach ($items as $item) {
            if ($this->isActive($item)) {
                return true;
            }
        }

        return false;
    }

    private function isExplicitActive($active)
    {
        foreach ($active as $url) {
            if ($this->checkExact($url)) {
                return true;
            }
        }

        return false;
    }
}

<?php

namespace JeroenNoten\LaravelAdminLte\Menu;

use Illuminate\Contracts\Routing\UrlGenerator;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ActiveChecker
{
    private $request;

    private $url;

    public function __construct(Request $request, UrlGenerator $url)
    {
        $this->request = $request;
        $this->url = $url;
    }

    public function isActive($item)
    {
        if (isset($item['active'])) {
            return $this->isExplicitActive($item['active']);
        }

        if (isset($item['submenu'])) {
            return $this->containsActive($item['submenu']);
        }

        if (isset($item['url'])) {
            return $this->checkExact($item['url']) || $this->checkSub($item['url']);
        }

        return false;
    }

    protected function checkExact($url)
    {
        return $this->checkPattern($url);
    }

    protected function checkSub($url)
    {
        return $this->checkPattern($url.'/*');
    }

    protected function checkPattern($pattern)
    {
        $fullUrlPattern = $this->url->to($pattern);

        $fullUrl = $this->request->fullUrl();

        return Str::is($fullUrlPattern, $fullUrl);
    }

    protected function containsActive($items)
    {
        foreach ($items as $item) {
            if ($this->isActive($item)) {
                return true;
            }
        }

        return false;
    }

    private function isExplicitActive($active)
    {
        foreach ($active as $url) {
            if ($this->checkExact($url)) {
                return true;
            }
        }

        return false;
    }
}

Fix for old versions of Laravel

Fix for old versions of Laravel


<?php namespace Calotype\SEO\Contracts;

interface MetaAware
{
    public function getMetaTitle();
    public function getMetaTitleSuffix();
    public function getMetaDescription();
}

<?php namespace Calotype\SEO\Contracts;

interface MetaAware
{
    /**
     * Get the data for the meta fields.
     *
     * <code>
     * $data = array(
     *     'title' => 'About us',
     *     'description' => 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.'
     * );
     * </code>
     *
     * @return array
     */
    public function getMetaData();
}

Make meta aware contract only require one function for forward compatibility.


<?php

namespace Djebbz\TicketBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/hello/Fabien');

        $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
    }
}

<?php

namespace Djebbz\TicketBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $browser = $client->request('GET', '/home');

        $this->assertTrue($client->getResponse()->isSuccessful());
    }
}

Test home route for 200 response code

Test home route for 200 response code


<?php

namespace Michaeljennings\Refinery\Contracts;

interface Refinery
{
    /**
     * Refine the item(s) using the set template.
     *
     * @param  mixed $raw
     * @return mixed
     */
    public function refine($raw);

    /**
     * Refine a collection of raw items.
     *
     * @param  mixed $raw
     * @return array
     */
    public function refineCollection($raw);

    /**
     * Set the attachments you want to bring with the refined items.
     *
     * @param  string|array $attachments
     * @return $this
     */
    public function bring($attachments);

    /**
     * Set the class to be used for the attachment.
     *
     * @param string        $className
     * @param callable|bool $callback
     * @return array
     * @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound
     */
    public function attach($className, callable $callback = false);

    /**
     * Alias for the attach method.
     *
     * @param string   $className
     * @param callable $callback
     * @return array
     * @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound
     */
    public function embed($className, callable $callback = false);

    /**
     * Alias for the attach method.
     *
     * @param string   $className
     * @param callable $callback
     * @return array
     * @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound
     */
    public function nest($className, callable $callback = false)
}

<?php

namespace Michaeljennings\Refinery\Contracts;

interface Refinery
{
    /**
     * Refine the item(s) using the set template.
     *
     * @param  mixed $raw
     * @return mixed
     */
    public function refine($raw);

    /**
     * Refine a collection of raw items.
     *
     * @param  mixed $raw
     * @return array
     */
    public function refineCollection($raw);

    /**
     * Set the attachments you want to bring with the refined items.
     *
     * @param  string|array $attachments
     * @return $this
     */
    public function bring($attachments);

    /**
     * Set the class to be used for the attachment.
     *
     * @param string        $className
     * @param callable|bool $callback
     * @return array
     * @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound
     */
    public function attach($className, callable $callback = false);

    /**
     * Alias for the attach method.
     *
     * @param string   $className
     * @param callable $callback
     * @return array
     * @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound
     */
    public function embed($className, callable $callback = false);

    /**
     * Alias for the attach method.
     *
     * @param string   $className
     * @param callable $callback
     * @return array
     * @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFoundg
     */
    public function nest($className, callable $callback = false);
}

Fix issue in refinery contract

Fix issue in refinery contract


                    id}}" class="note-title">
                        {{ $notes->notes_title }}

                    id}}" class="note-title direction">

Replace the double arrow on collection with circle


<a href="<?php echo home_url(); ?>"><img class="blogroll_logo small-8 small-centered medium-12 columns" src="<?php echo get_template_directory_uri(); ?>/assets/img/blogroll-logo.svg" title="<?php bloginfo('name'); ?>" alt="<?php bloginfo('name'); ?>">

	<?php do_action('foundationPress_before_sidebar'); ?>
	<?php dynamic_sidebar("sidebar-widgets"); ?>
	<?php do_action('foundationPress_after_sidebar'); ?>

<a href="<?php echo home_url(); ?>"><img class="blogroll_logo small-8 small-centered medium-12 columns" src="<?php echo get_template_directory_uri(); ?>/assets/img/blogroll-logo.svg" title="<?php bloginfo('name'); ?>" alt="<?php bloginfo('name'); ?>">

Does this update?

	<?php do_action('foundationPress_before_sidebar'); ?>
	<?php dynamic_sidebar("sidebar-widgets"); ?>
	<?php do_action('foundationPress_after_sidebar'); ?>

Test for updating production site

Test for updating production site


<?php namespace Illuminate\Html;

use Illuminate\Support\ServiceProvider;

class HtmlServiceProvider extends ServiceProvider {

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['form'] = $this->app->share(function($app)
		{
			return new FormBuilder($app['url'], $app['session']->getToken());
		});
	}

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

}

<?php namespace Illuminate\Html;

use Illuminate\Support\ServiceProvider;

class HtmlServiceProvider extends ServiceProvider {

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['form'] = $this->app->share(function($app)
		{
			$form = new FormBuilder($app['url'], $app['session']->getToken());

			$form->setSessionStore($app['session']);

			return $form;
		});
	}

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

}

Set session on form builder.

Set session on form builder.


<?php

namespace InvalidPhpDoc;

/**
 * @param string $unknown
 * @param int $a
 * @param array $b
 * @param array $c
 * @param int|float $d
 */
function paramTest(int $a, string $b, iterable $c, int $d)
{

}

/**
 * @param int ...$numbers invalid according to PhpStorm, but actually valid
 */
function variadicNumbers(int ...$numbers)
{

}

/**
 * @param string[] ...$strings valid according to PhpStorm, but actually invalid
 */
function variadicStrings(string ...$strings)
{

}

/**
 * @return int
 */
function testReturnIntOk(): int
{

}

/**
 * @return bool
 */
function testReturnBoolOk(): bool
{

}

/**
 * @return true
 */
function testReturnTrueOk(): bool
{

}

/**
 * @return string
 */
function testReturnIntInvalid(): int
{

}

/**
 * @return string|int
 */
function testReturnIntNotSubset(): int
{

}

/**
 * @param string[] $strings
 */
function anotherVariadicStrings(string ...$strings)
{

}

Test - possibly correct syntax for variadic parameter in phpDoc


<?php
/**
 * @file
 * Contains \Drupal\AppConsole\EventSubscriber\CallCommandListener.
 */

namespace Drupal\AppConsole\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Input\ArrayInput;
use Drupal\AppConsole\Command\Command;
use Symfony\Component\Console\ConsoleEvents;

class CallCommandListener implements EventSubscriberInterface
{
    /**
     * @param ConsoleTerminateEvent $event
     */
    public function callCommands(ConsoleTerminateEvent $event)
    {
        /** @var \Drupal\AppConsole\Command\Command $command */
        $command = $event->getCommand();
        $output = $event->getOutput();

        if (!$command instanceof Command) {
            return;
        }

        $commands = $command->getHelper('chain')->getCommands();

        if (!$commands) {
            return;
        }

        $application = $command->getApplication();
        foreach ($commands as $chainedCommand) {
            $callCommand = $application->find($chainedCommand['name']);

            $input = new ArrayInput($chainedCommand['arguments']);
            $callCommand->run($input, $output);
        }
    }

    /**
     * @{@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [ConsoleEvents::TERMINATE => 'callCommands'];
    }
}

<?php
/**
 * @file
 * Contains \Drupal\AppConsole\EventSubscriber\CallCommandListener.
 */

namespace Drupal\AppConsole\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Input\ArrayInput;
use Drupal\AppConsole\Command\Command;
use Symfony\Component\Console\ConsoleEvents;

class CallCommandListener implements EventSubscriberInterface
{
    /**
     * @param ConsoleTerminateEvent $event
     */
    public function callCommands(ConsoleTerminateEvent $event)
    {
        /** @var \Drupal\AppConsole\Command\Command $command */
        $command = $event->getCommand();
        $output = $event->getOutput();

        if (!$command instanceof Command) {
            return;
        }

        $commands = $command->getHelper('chain')->getCommands();

        if (!$commands) {
            return;
        }

        $application = $command->getApplication();
        foreach ($commands as $chainedCommand) {
            $callCommand = $application->find($chainedCommand['name']);

            $input = new ArrayInput($chainedCommand['inputs']);
            $callCommand->run($input, $output);
        }
    }

    /**
     * @{@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [ConsoleEvents::TERMINATE => 'callCommands'];
    }
}

Update call to arguments to inputs

Update call to arguments to inputs


<?php

namespace TM\ErrorLogParser\Exception;

/**
 * Class FormatException
 *
 * @package TM\ErrorLogParser\Exception
 */
class FormatException extends \Exception
{
    /**
     * @var string
     */
    public $message =
        'The parser only supports the default Log-Format!' . PHP_EOL .
        'If you think this is an error please refer to' . PHP_EOL .
        'https://github.com/tommy-muehle/error-log-parser/issues' . PHP_EOL .
        'and create an issue!';
}

<?php

namespace TM\ErrorLogParser\Exception;

/**
 * Class FormatException
 *
 * @package TM\ErrorLogParser\Exception
 */
class FormatException extends \Exception
{
    /**
     * @param string     $message
     * @param int        $code
     * @param \Exception $previous
     */
    public function __construct($message = null, $code = null, \Exception $previous = null)
    {
        $message = '
            The parser only supports the default Log-Format!' . PHP_EOL . '
            If you think this is an error please refer to' . PHP_EOL . '
            https://github.com/tommy-muehle/error-log-parser/issues' . PHP_EOL . '
            and create an issue!
        ';

        parent::__construct($message, $code, $previous);
    }

}

Fix message format in exception to prevent failure in PHP 5.5


<?php
require '../assets/includes/connect.php';

$project_comments = file_get_html('https://scratch.mit.edu/site-api/comments/project/47606468/'.'?_='.mt_rand());
$comments = $project_comments -> find('.comment .info');
$is_good_reg = false;
foreach ($comments as $comment) {
	$creator = trim($comment -> find('.name', 0) -> plaintext);
	$content = trim($comment -> find('.content', 0) -> plaintext);
	if ($creator == $_GET['user'] && $content == $_GET['key']) {
		$is_good_reg = true;
		break;
	}
}

echo json_encode($is_good_reg);

?>

<?php
require '../assets/includes/connect.php';

$project_comments = file_get_html('https://scratch.mit.edu/site-api/comments/project/47606468/'.'?_='.mt_rand());
$comments = $project_comments -> find('.comment .info');
$is_good_reg = false;
foreach ($comments as $comment) {
	$creator = trim($comment -> find('.name', 0) -> plaintext);
	$content = trim($comment -> find('.content', 0) -> plaintext);
	if ($creator == $_GET['user'] && ( $content == $_GET['key'] || $content == "\"" . $_GET['key'] . "\"" ) ) {
		$is_good_reg = true;
		break;
	}
}

echo json_encode($is_good_reg);

?>

Check for key in quotes too

Check for key in quotes too

This may be useful for all those people who don't understand... :package:


## {{$endpoint->getName()}}

`{{$endpoint->getMethod()}} {{$endpoint->getUri()}}`

{!! $endpoint->getDescription() !!}

@if (count($endpoint->getParams()) > 0)
### Parameters

| Name | Located in | Description | Type |
| ---- | ---------- | ----------- | ---- |
@foreach ($endpoint->getParams() as $param)
|{{$param->name}}|{{$param->in}}|{{$param->description}}|{{$param->type}}|
@endforeach
@endif

@if ($endpoint->getReturn()->getType() == CodeOrange\Jot\Docs\ReturnValue::$JSON)
```json
{!! $endpoint->getReturn()->getValue() !!}
```

@else()
### Response

{{$endpoint->getReturn()->getValue()}}
@endif

## {{$endpoint->getName()}}

`{{$endpoint->getMethod()}} {{$endpoint->getUri()}}`

{!! $endpoint->getDescription() !!}

@if (count($endpoint->getParams()) > 0)
### Parameters

| Name | Located in | Description | Type |
| ---- | ---------- | ----------- | ---- |
@foreach ($endpoint->getParams() as $param)
|{{$param->name}}|{{$param->in}}|{{$param->description}}|{{$param->type}}|
@endforeach
@endif

@if ($endpoint->getReturn()->getType() == CodeOrange\Jot\Docs\ReturnValue::$JSON)
> Response

```json
{!! $endpoint->getReturn()->getValue() !!}
```

@else()
### Response

{{$endpoint->getReturn()->getValue()}}
@endif

Add Response header to JSON response

Add Response header to JSON response


<?php namespace Flarum\Api\Actions;

use Flarum\Api\Request;
use Zend\Diactoros\Response;

abstract class DeleteAction extends JsonApiAction
{
    /**
     * Delegate deletion of the resource, and return a 204 No Content
     * response.
     *
     * @param \Flarum\Api\Request $request
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function respond(Request $request)
    {
        $this->delete($request);

        return new Response('', 204);
    }

    /**
     * Delete the resource.
     *
     * @param \Flarum\Api\Request $request
     * @return void
     */
    abstract protected function delete(Request $request);
}

<?php namespace Flarum\Api\Actions;

use Flarum\Api\Request;
use Zend\Diactoros\Response;

abstract class DeleteAction extends JsonApiAction
{
    /**
     * Delegate deletion of the resource, and return a 204 No Content
     * response.
     *
     * @param \Flarum\Api\Request $request
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function respond(Request $request)
    {
        $this->delete($request);

        return new Response('php://memory', 204);
    }

    /**
     * Delete the resource.
     *
     * @param \Flarum\Api\Request $request
     * @return void
     */
    abstract protected function delete(Request $request);
}

Fix fatal error on delete actions

Fix fatal error on delete actions


<?php

namespace ForkCMS\Bundle\InstallerBundle\Form\Handler;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

/**
 * Validates and saves the data from the modules form
 *
 * @author Wouter Sioen <wouter.sioen@wijs.be>
 */
class ModulesHandler
{
    public function process(Form $form, Request $request)
    {
        if (!$request->isMethod('POST')) {
            return false;
        }

        $form->handleRequest($request);

        if ($form->isValid()) {
            return $this->processValidForm($form, $request);
        }

        return false;
    }

    public function processValidForm(Form $form, $request)
    {
        $session = $request->getSession();
        $data = $form->getData();

        $session->set('modules', $data['modules']);
        $session->set('example_data', $data['example_data']);
        $session->set('different_debug_email', $data['different_debug_email']);
        $session->set('debug_email', $data['debug_email']);

        return true;
    }
}

<?php

namespace ForkCMS\Bundle\InstallerBundle\Form\Handler;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

/**
 * Validates and saves the data from the modules form
 *
 * @author Wouter Sioen <wouter.sioen@wijs.be>
 */
class ModulesHandler
{
    public function process(Form $form, Request $request)
    {
        if (!$request->isMethod('POST')) {
            return false;
        }

        $form->handleRequest($request);

        if ($form->isValid()) {
            return $this->processValidForm($form, $request);
        }

        return false;
    }

    public function processValidForm(Form $form, $request)
    {
        $session = $request->getSession();
        $data = $form->getData();

        if ($data['example_data'] === true && !in_array('Blog', $data['modules'])) {
            $data['modules'][] = 'Blog';
        }

        $session->set('modules', $data['modules']);
        $session->set('example_data', $data['example_data']);
        $session->set('different_debug_email', $data['different_debug_email']);
        $session->set('debug_email', $data['debug_email']);

        return true;
    }
}

Install Blog when example data is wanted.


<?php

namespace App;

use Carbon\Carbon;
use App\BookingStrategyTimeslot;
use App\BookingStrategyDateslot;

class BookingStrategy
{
    private $strategy = null;

    public function __construct($strategyId)
    {
        switch ($strategyId) {
            case 'timeslot': $this->strategy = new BookingStrategyTimeslot(); break;
            case 'dateslot': $this->strategy = new BookingStrategyDateslot(); break;
            default:
                Log::warning("BookingStrategy: __construct: Illegal strategy:{$this->strategy}");
            break;
        }
    }

    public function makeReservation(User $issuer, Business $business, $data)
    {
        return $this->strategy->makeReservation($issuer, $business, $data);
    }
}

interface BookingStrategyInterface
{
    public function makeReservation(User $issuer, Business $business, $data);
}

<?php

namespace App;

use Carbon\Carbon;
use App\BookingStrategyTimeslot;
use App\BookingStrategyDateslot;
use Log;

class BookingStrategy
{
    private $strategy = null;

    public function __construct($strategyId)
    {
        switch ($strategyId) {
            case 'timeslot':
                $this->strategy = new BookingStrategyTimeslot();
            break;
            case 'dateslot':
                $this->strategy = new BookingStrategyDateslot();
            break;
            default:
                Log::warning("BookingStrategy: __construct: Illegal strategy:{$this->strategy}");
            break;
        }
    }

    public function makeReservation(User $issuer, Business $business, $data)
    {
        return $this->strategy->makeReservation($issuer, $business, $data);
    }
}

interface BookingStrategyInterface
{
    public function makeReservation(User $issuer, Business $business, $data);
}

Enhance coding style and add use Log

Enhance coding style and add use Log

https://codeclimate.com/github/alariva/timegrid/app/BookingStrategy.php#all


<?php

namespace App\Models\Web;

use App\Models\WebModel;

/**
 * Page on the website
 */
class Page extends WebModel
{

    protected $hasSourceDates = false;

    protected $casts = [
        'publish_start_date' => 'datetime',
        'publish_end_date' => 'datetime',
        'is_published' => 'boolean',
    ];

}

<?php

namespace App\Models\Web;

use App\Models\WebModel;

/**
 * Page on the website
 */
class Page extends WebModel
{

    protected $casts = [
        'publish_start_date' => 'datetime',
        'publish_end_date' => 'datetime',
        'is_published' => 'boolean',
    ];

}

Fix lastmod date error for web pages

Fix lastmod date error for web pages [WEB-1445]


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

<?php echo esc_html(get_permalink()) ?>

<?php the_title() ?>

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

      <?php the_content() ?>

        <?php echo get_the_tag_list('
Tags: ', ',', '
'); ?>

  <?php share_icons(get_the_ID()) ?>
  <?php comments_template('/templates/comments.php') ?>
<?php endwhile ?>

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

<?php echo esc_html(get_permalink()) ?>

<?php the_title() ?>

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

      <?php the_content() ?>

        <?php echo get_the_tag_list('
Tags: ', ',', '
'); ?>

      <?php previous_post_link() ?>

      <?php next_post_link() ?>

  <?php share_icons(get_the_ID()) ?>
  <?php comments_template('/templates/comments.php') ?>
<?php endwhile ?>

Add some basic previous/next links

Add some basic previous/next links


<?php

declare(strict_types=1);

namespace Sylius\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20200309172908 extends AbstractMigration
{
    public function getDescription() : string
    {
        return '';
    }

    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_product_variant ADD enabled TINYINT(1) NOT NULL');
    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_product_variant DROP enabled');
    }
}

<?php

declare(strict_types=1);

namespace Sylius\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20200309172908 extends AbstractMigration
{
    public function getDescription() : string
    {
        return '';
    }

    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_product_variant ADD enabled TINYINT(1) NOT NULL');
        $this->addSql('UPDATE sylius_product_variant SET enabled = 1');
    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_product_variant DROP enabled');
    }
}

Add statement to toggleable variant migration to enable existing


<?php

/*
 * This file is part of Twig.
 *
 * (c) Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Twig\Extra\TwigExtraBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Twig\Extra\TwigExtraBundle\Extensions;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('twig_extra');
        $rootNode = $treeBuilder->getRootNode();

        foreach (Extensions::getClasses() as $name => $class) {
            $rootNode
                ->children()
                    ->arrayNode($name)
                        ->{class_exists($class) ? 'canBeDisabled' : 'canBeEnabled'}()
                    ->end()
                ->end()
            ;
        }

        return $treeBuilder;
    }
}

<?php

/*
 * This file is part of Twig.
 *
 * (c) Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Twig\Extra\TwigExtraBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Twig\Extra\TwigExtraBundle\Extensions;

class Configuration implements ConfigurationInterface
{
    /**
     * @return TreeBuilder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('twig_extra');
        $rootNode = $treeBuilder->getRootNode();

        foreach (Extensions::getClasses() as $name => $class) {
            $rootNode
                ->children()
                    ->arrayNode($name)
                        ->{class_exists($class) ? 'canBeDisabled' : 'canBeEnabled'}()
                    ->end()
                ->end()
            ;
        }

        return $treeBuilder;
    }
}

[TwigExtraBundle] Add the return type information in getConfigTreeBuilder()


<?php

namespace GarageDoorHacks\Service;

use Symfony\Component\Process\Process;

class DoorService
{
    public function open()
    {
        $initGpioProcess = new Process('gpio mode 0 out');
        $initGpioProcess->run();

        $openCommandProcess = new Process('gpio write 0 1 && sleep 3 && gpio write 0 0');
        $openCommandProcess->start();
    }
}

<?php

namespace GarageDoorHacks\Service;

use Symfony\Component\Process\Process;

class DoorService
{
    public function open()
    {
        $initGpioProcess = new Process('gpio mode 0 out');
        $initGpioProcess->run();

        $openCommandProcess = new Process('gpio write 0 1 && sleep 3 && gpio write 0 0');
        $openCommandProcess->run();
    }
}

Fix process killed too soon

Fix process killed too soon


<?php

final class PhabricatorTransactionsFulltextEngineExtension
  extends PhabricatorFulltextEngineExtension {

  const EXTENSIONKEY = 'transactions';

  public function getExtensionName() {
    return pht('Comments');
  }

  public function shouldEnrichFulltextObject($object) {
    return ($object instanceof PhabricatorApplicationTransactionInterface);
  }

  public function enrichFulltextObject(
    $object,
    PhabricatorSearchAbstractDocument $document) {

    $query = PhabricatorApplicationTransactionQuery::newQueryForObject($object);
    if (!$query) {
      return;
    }

    $xactions = $query
      ->setViewer($this->getViewer())
      ->withObjectPHIDs(array($object->getPHID()))
      ->withComments(true)
      ->needComments(true)
      ->execute();

    foreach ($xactions as $xaction) {
      if (!$xaction->hasComment()) {
        continue;
      }

      $comment = $xaction->getComment();

      $document->addField(
        PhabricatorSearchDocumentFieldType::FIELD_COMMENT,
        $comment->getContent());
    }
  }

}

<?php

final class PhabricatorTransactionsFulltextEngineExtension
  extends PhabricatorFulltextEngineExtension {

  const EXTENSIONKEY = 'transactions';

  public function getExtensionName() {
    return pht('Comments');
  }

  public function shouldEnrichFulltextObject($object) {
    return ($object instanceof PhabricatorApplicationTransactionInterface);
  }

  public function enrichFulltextObject(
    $object,
    PhabricatorSearchAbstractDocument $document) {

    $query = PhabricatorApplicationTransactionQuery::newQueryForObject($object);
    if (!$query) {
      return;
    }

    $query
      ->setViewer($this->getViewer())
      ->withObjectPHIDs(array($object->getPHID()))
      ->withComments(true)
      ->needComments(true);

    // See PHI719. Users occasionally create objects with huge numbers of
    // comments, which can be slow to index. We handle this with reasonable
    // grace: at time of writing, we can index a task with 100K comments in
    // about 30 seconds. However, we do need to hold all the comments in
    // memory in the AbstractDocument, so there's some practical limit to what
    // we can realistically index.

    // Since objects with more than 1,000 comments are not likely to be
    // legitimate objects with actual discussion, index only the first
    // thousand comments.

    $query
      ->setOrderVector(array('-id'))
      ->setLimit(1000);

    $xactions = $query->execute();

    foreach ($xactions as $xaction) {
      if (!$xaction->hasComment()) {
        continue;
      }

      $comment = $xaction->getComment();

      $document->addField(
        PhabricatorSearchDocumentFieldType::FIELD_COMMENT,
        $comment->getContent());
    }
  }

}

Index only the first 1,000 comments on any object

Summary:
Depends on D19502. Ref T13151. See PHI719. An install ended up with an object with 111,000+ comments on it because someone wrote a script to treat it like a logfile.

Although we seem to do mostly okay with this (locally, it only takes about 30s to index a similar object) we'll hit a wall somewhere (since we need to hold everything in memory), and it's hard to imagine a legitimate object with more than 1,000 comments. Just ignore comments past the first thousand.

(Conpherence threads may legitimately have more than 1,000 comments, but go through a different indexer.)

Test Plan:
  - Piped some comments into `maniphest.edit` in a loop to create a task with 100K comments.
  - Ran `bin/search index Txxx --force` to reindex it, with `--trace`.
    - Before: task indexed in about 30s.
    - After: script loaded comments with LIMIT 1000 and indexed in a couple seconds.

Reviewers: amckinley

Reviewed By: amckinley

Maniphest Tasks: T13151

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


<?php

/**
 * @example
 * FastForward::Helpers()
 *     ->renderImage(142, 'full');
 */
class FastForward_Helpers {
    public function renderImage($id, $size = 'thumbnail') {
        echo wp_get_attachment_image($id, $size);
    }

    public function getImageAllSizes($id, $custom = array()) {
        $thumbnail = wp_get_attachment_image_src($id, 'thumbnail');
        $medium = wp_get_attachment_image_src($id, 'medium');
        $large = wp_get_attachment_image_src($id, 'large');
        $full = wp_get_attachment_image_src($id, 'full');

        if ($custom) {
            $customSize = wp_get_attachment_image_src($id, array($custom[0], $custom[1]));
        }

        $set = array(
            'thumbnail' => $thumbnail,
            'medium' => $medium,
            'large' => $large,
            'full' => $full,
            'custom' => $customSize
        );

        return $set;
    }

    public function help() {
        global $FastForward;
        $methods = array();

        foreach ($FastForward as $obj) {
            $methods[get_class($obj)] = get_class_methods($obj);
        }

        echo '<pre>';
        print_r($methods);
        echo '</pre>';
    }
}

<?php

/**
 * @example
 * FastForward::Helpers()
 *     ->renderImage(142, 'full');
 */
class FastForward_Helpers {
    public function renderImage($id, $size = 'thumbnail') {
        echo wp_get_attachment_image($id, $size);
    }

    public function getImageAllSizes($id, $custom = array()) {
        $thumbnail = wp_get_attachment_image_src($id, 'thumbnail');
        $medium = wp_get_attachment_image_src($id, 'medium');
        $large = wp_get_attachment_image_src($id, 'large');
        $full = wp_get_attachment_image_src($id, 'full');

        if ($custom) {
            $customSize = wp_get_attachment_image_src($id, array($custom[0], $custom[1]));
        }

        $set = array(
            'thumbnail' => $thumbnail,
            'medium' => $medium,
            'large' => $large,
            'full' => $full,
            'custom' => $customSize
        );

        return $set;
    }

    public function getSinglePost($args) {
        $args = wp_parse_args($args, array(
            'posts_per_page' => 1
        ));

        $results = get_pages($args);

        return $results[0];
    }

    public function help() {
        global $FastForward;
        $methods = array();

        foreach ($FastForward as $obj) {
            $methods[get_class($obj)] = get_class_methods($obj);
        }

        echo '<pre>';
        print_r($methods);
        echo '</pre>';
    }
}

Add helper: get single post

Add helper: get single post


<?php

namespace Zeropingheroes\Lanager\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Game extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'url' => $this->url(),
            'logo' => [
                'small' => $this->logo('small'),
                'medium' => $this->logo('medium'),
                'large' => $this->logo('large'),
            ],
            'links' => [
                'self' => route('api.games.show', ['game' => $this->id]),
            ],
        ];
    }
}

<?php

namespace Zeropingheroes\Lanager\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Game extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'provider' => 'steam',
            'url' => $this->url(),
            'logo' => [
                'small' => $this->logo('small'),
                'medium' => $this->logo('medium'),
                'large' => $this->logo('large'),
            ],
            'links' => [
                'self' => route('api.games.show', ['game' => $this->id]),
            ],
        ];
    }
}

Add provider field for future use

Add provider field for future use


@lang('soda::terminology.quicklink_plural')

    @foreach(app('soda.interface')->quicklinks() as $quicklink)
        getUrl() }}" class="tag">
          {{ $quicklink->text }}
          @if($quicklink->user_id == Auth::guard('soda')->user()->id)
          ×
          @endif

    @endforeach

<?php
$quicklinks = app('soda.interface')->quicklinks();
?>

@if(count($quicklinks))

@lang('soda::terminology.quicklink_plural')

        @foreach($quicklinks as $quicklink)
            getUrl() }}" class="tag">
                {{ $quicklink->text }}
                @if($quicklink->user_id == Auth::guard('soda')->user()->id)
                    ×
                @endif

        @endforeach

@endif

Hide quicklinks dashboard item if none set


<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->integer('tipo');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('usuarios', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nombre');
            $table->string('email')->unique();
            $table->string('password');
            $table->integer('tipo');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Fix - Cambio nombre de tabla

Fix - Cambio nombre de tabla


<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->engine = 'InnoDB';
        });
    }

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

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->engine = 'InnoDB';
        });
    }

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

Use increments() instead of id() for users.id column


<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('api_token')->unique()->nullable()->default(null);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('api_token')->unique()->nullable()->default(null);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Upgrade to Laravel 7: Updating create_users_table migration id column to bigIncrements()


<?php

use PHPUnit\Framework\TestCase;

/**
 * @covers DNASequence
 */
class DNASequenceTest extends TestCase
{
    /**
     * @covers DNASequence::findRestrictionSites
     */
    public function testDoesNotMutate()
    {
        $dnaSequence = 'ATTAATAGGTATCCGGGATATATAT'; // Should never be mutated when checked against ASP718I and TspMI.
        $sites = array(
            RestrictionSites::getSiteByName('ASP718I'),
            RestrictionSites::getSiteByName('TspMI')
        );
        $dna = new DNASequence($dnaSequence);
        $dna->findRestrictionSites($sites);
        $result = $dna->getResult();
        $this->assertEquals('ATTAATAGGTATCCGGGATATATAT', $result->raw);
    }

    /**
     * @covers DNAResult
     * @covers DNASequence::findRestrictionSites
     */
    public function testCorrectMutation()
    {
        $dnaSequence = 'ATATGGGCCCATGCC';
        $formattedExpected = "ATATGGGCTCATGCC";
        $dna = new DNASequence($dnaSequence);
        $sites = array(RestrictionSites::getSite("GGGCCC"));

        $dna->findRestrictionSites($sites);
        $result = $dna->getResult();
        $this->assertEquals('ATATGGGCTCATGCC', $result->raw);
        $this->assertEquals($formattedExpected, $result->formatted);
    }
}

<?php

use PHPUnit\Framework\TestCase;

/**
 * @covers DNASequence
 */
class DNASequenceTest extends TestCase
{
    /**
     * @covers DNASequence::findRestrictionSites
     */
    public function testDoesNotMutate()
    {
        $dnaSequence = 'ATTAATAGGTATCCGGGATATATAT'; // Should never be mutated when checked against ASP718I and TspMI.
        $sites = array(
            RestrictionSites::getSiteByName('ASP718I'),
            RestrictionSites::getSiteByName('TspMI')
        );
        $dna = new DNASequence($dnaSequence);
        $dna->findRestrictionSites($sites);
        $result = $dna->getResult();
        $this->assertEquals('ATTAATAGGTATCCGGGATATATAT', $result->raw);
    }
}

Remove test that could cause phpunit to fail due to the random nature of silent mutaitons.


<?php

namespace Trademachines\Riemann;

trait RiemannAwareTrait
{
    /**
     * @var Client
     */
    protected $riemannClient;

    /**
     * @param Client $riemannClient
     */
    public function setClient(Client $riemannClient)
    {
        $this->riemannClient = $riemannClient;
    }
}

<?php

namespace Trademachines\Riemann;

trait RiemannAwareTrait
{
    /**
     * @var Client
     */
    protected $riemannClient;

    /**
     * @param Client $riemannClient
     */
    public function setRiemannClient(Client $riemannClient)
    {
        $this->riemannClient = $riemannClient;
    }
}

Change to a more explicit setter name

Change to a more explicit setter name


<?php

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

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

// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.
/*
$loader = new ApcClassLoader('sf2', $loader);
$loader->register(true);
*/

require_once __DIR__ . '/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;

require_once __DIR__ . '/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$kernel = new AppCache($kernel);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Use the AppCache Kernel in production

Use the AppCache Kernel in production


@extends('layout')

@section('title')File - {{$file}}@stop

@section('content')

{{SourceController::linkedPath($path)}}

Query

    <?php
	    $source = file_get_contents(base_path() . "/query/" . $file . ".sql");
    	$geshi = new GeSHi($source, 'sql');
    	echo $geshi->parse_code();
    ?>

Output

    <?php
    	$outputs = SourceController::getDir("output/" . $path);
    	$filename = $outputs[sizeof($outputs) - 1];

	    $source = file_get_contents(base_path() . "/output/" . $file . "/" . $filename);
    	$geshi = new GeSHi($source, 'sql');
    	echo $geshi->parse_code();
    ?>

@stop

@extends('layout')

@section('title')File - {{$file}}@stop

@section('content')

{{SourceController::linkedPath($path)}}

Query

    <?php
	    $source = file_get_contents(base_path() . "/query/" . $file . ".sql");
    	$geshi = new GeSHi(trim($source), 'sql');
    	echo $geshi->parse_code();
    ?>

Output

    <?php
    	$outputs = SourceController::getDir("output/" . $path);
    	$filename = $outputs[sizeof($outputs) - 1];

	    $source = file_get_contents(base_path() . "/output/" . $file . "/" . $filename);
    	$geshi = new GeSHi(trim($source), 'sql');
    	echo $geshi->parse_code();
    ?>

@stop

Remove blank lines at the begin or the end of the imported file


                <?php bloginfo("name") ?>

                <?php bloginfo("description") ?>

              Download

<?php while (have_posts()) : the_post(); ?>
    <?php remove_filter( 'the_content', 'wpautop' ); ?>
    <?php the_content(); ?>
    <?php wp_link_pages(array('before' => '', 'after' => '')); ?>
<?php endwhile; ?>

Revert "Tweaked with header a bit"

Revert "Tweaked with header a bit"

This reverts commit b00daf557e643f477109164091778effed450b10.


<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';

class OrganismsTest extends PHPUnit_Framework_TestCase
{
    public function testExecute()
    {
        list($service) = \WebService::factory('listing/Organisms');

        $results = ($service->execute(array('limit' => 2)));
        $this->assertEquals(2, count($results));

        $results = ($service->execute(array()));
        $this->assertEquals(5, count($results));

        $results = ($service->execute(array('limit' => 10000000)));
        $this->assertEquals(12, count($results));

    }
}
?>

<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';

class OrganismsTest extends PHPUnit_Framework_TestCase
{
    public function testExecute()
    {
        list($service) = \WebService::factory('listing/Organisms');

        $results = ($service->execute(array('limit' => 2)));
        $this->assertEquals(2, count($results));

        $results = ($service->execute(array()));
        $this->assertEquals(5, count($results));

        $organism = 'Thermopsis';
        $results = ($service->execute(array('limit' => 1, 'search' => $organism)));
        $this->assertEquals(1, count($results));
        $pos = strpos($organism, $results);
        $this->assertEquals(1, $pos);

    }
}
?>

Add one more test for checking the search functionality of the organism webservice


<?php

Route::filter('logviewer.logs', function()
{
    $logs = array();
    foreach (Lang::get('logviewer::logviewer.sapi') as $sapi => $human)
    {
        $logs[$sapi]['sapi'] = $human;
        $files = array_reverse(glob(storage_path().'/logs/log-'.$sapi.'*'));
        foreach ($files as &$file)
        {
            $file = preg_replace('/log-.+?-/', '', basename($file, '.txt'));
            // $file = preg_replace('/.*(\d{4}-\d{2}-\d{2}).*/', '$1', basename($file)); // Is this faster?
        }
        $logs[$sapi]['logs'] = $files;
    }

    View::share('logs', $logs);
});

Route::filter('logviewer.messages', function()
{
    if (Session::has('success') OR Session::has('error') OR Session::has('info'))
    {
        View::share('has_messages', true);
    }
    else
    {
        View::share('has_messages', false);
    }
});

<?php

Route::filter('logviewer.logs', function()
{
    $logs = array();
    foreach (Lang::get('logviewer::logviewer.sapi') as $sapi => $human)
    {
        $logs[$sapi]['sapi'] = $human;
        $files = array_reverse(glob(storage_path().'/logs/log-'.$sapi.'*'));
        foreach ($files as &$file)
        {
            $file = preg_replace('/.*(\d{4}-\d{2}-\d{2}).*/', '$1', basename($file));
        }
        $logs[$sapi]['logs'] = $files;
    }

    View::share('logs', $logs);
});

Route::filter('logviewer.messages', function()
{
    if (Session::has('success') OR Session::has('error') OR Session::has('info'))
    {
        View::share('has_messages', true);
    }
    else
    {
        View::share('has_messages', false);
    }
});

Fix log aggregation for Fast CGI

Fix log aggregation for Fast CGI


<?php

namespace SeatGeek\Sixpack\Test\Session;

use \PHPUnit_Framework_TestCase;

class BaseTest extends PHPUnit_Framework_TestCase
{
}

<?php

namespace SeatGeek\Sixpack\Test\Session;

use SeatGeek\Sixpack\Session\Base;
use \PHPUnit_Framework_TestCase;

class BaseTest extends PHPUnit_Framework_TestCase
{
    /**
     * Verify the mocked method call to sendRequest, and that the return value
     * is the right class
     */
    public function testParticipateValidArgs()
    {
        $base = $this->getMockBuilder('SeatGeek\Sixpack\Session\Base')
            ->disableOriginalConstructor()
            ->setMethods(['sendRequest'])
            ->getMock();

        $mockedResponse = [
            'raw response',
            ['meta', 'data']
        ];
        $base->expects($this->once())
            ->method('sendRequest')
            ->with(
                'participate',
                [
                    'experiment' => 'the',
                    'alternatives' => ['the', 'alternative'],
                    'traffic_fraction' => '0.42'
                ]
            )->will($this->returnValue($mockedResponse));

        $return = $base->participate('the', ['the', 'alternative'], 0.42);
        $this->assertInstanceOf('SeatGeek\Sixpack\Response\Participation', $return);
    }
}

Add a simple test verifying things normally work


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

require_once __DIR__.'/../Annotation.php';
require_once __DIR__.'/../Entity.php';
require_once __DIR__.'/../MappedSuperclass.php';
require_once __DIR__.'/../InheritanceType.php';
require_once __DIR__.'/../DiscriminatorColumn.php';
require_once __DIR__.'/../DiscriminatorMap.php';
require_once __DIR__.'/../Id.php';
require_once __DIR__.'/../GeneratedValue.php';
require_once __DIR__.'/../Version.php';
require_once __DIR__.'/../JoinColumn.php';
require_once __DIR__.'/../JoinColumns.php';
require_once __DIR__.'/../Column.php';
require_once __DIR__.'/../OneToOne.php';
require_once __DIR__.'/../OneToMany.php';
require_once __DIR__.'/../ManyToOne.php';
require_once __DIR__.'/../ManyToMany.php';
require_once __DIR__.'/../ElementCollection.php';
require_once __DIR__.'/../Table.php';
require_once __DIR__.'/../UniqueConstraint.php';
require_once __DIR__.'/../Index.php';
require_once __DIR__.'/../JoinTable.php';
require_once __DIR__.'/../SequenceGenerator.php';
require_once __DIR__.'/../ChangeTrackingPolicy.php';
require_once __DIR__.'/../OrderBy.php';
require_once __DIR__.'/../NamedQueries.php';
require_once __DIR__.'/../NamedQuery.php';
require_once __DIR__.'/../HasLifecycleCallbacks.php';
require_once __DIR__.'/../PrePersist.php';
require_once __DIR__.'/../PostPersist.php';
require_once __DIR__.'/../PreUpdate.php';
require_once __DIR__.'/../PostUpdate.php';
require_once __DIR__.'/../PreRemove.php';
require_once __DIR__.'/../PostRemove.php';
require_once __DIR__.'/../PostLoad.php';
require_once __DIR__.'/../PreFlush.php';

Add requires to new files for BC

Add requires to new files for BC


<?php namespace ThibaudDauce\EloquentInheritanceStorage;

class InheritanceStorage {

  /* Service status :
   * true : switch between view and storage table ON
   * false : switch between view and storage table OFF, only return storage table.
  **/
  static $activated = true;

  const VIEW_MODE    = 'view';
  const STORAGE_MODE = 'storage';

  /*
   * Getters for const values
  **/
  public function VIEW_MODE() {
    return self::VIEW_MODE;
  }

  public function STORAGE_MODE() {
    return self::STORAGE_MODE;
  }
}

<?php namespace ThibaudDauce\EloquentInheritanceStorage;

class InheritanceStorage {

  /* Service status :
   * true : switch between view and storage table ON
   * false : switch between view and storage table OFF, only return storage table.
  **/
  static $activated = true;

  const VIEW_MODE    = 'view';
  const STORAGE_MODE = 'storage';

  /*
   * Getters for const values
  **/
  public function VIEW_MODE() {
    return self::VIEW_MODE;
  }

  public function STORAGE_MODE() {
    return self::STORAGE_MODE;
  }

  public function activate() {
    self::$activated = true;
  }

  public function desactivate() {
    self::$activated = false;
  }
}

Add setters to activate or desactivate global inheritance storage


<?php

namespace wcf\system\language\preload\command;

use wcf\data\language\Language;
use wcf\system\event\EventHandler;
use wcf\system\language\preload\PreloadPhrasesCollecting;

/**
 * Rebuilds the phrase preload cache for the
 * requested language.
 *
 * @author Alexander Ebert
 * @copyright 2001-2022 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Language\Preload\Command
 * @since 6.0
 */
final class CachePreloadPhrases
{
    private readonly EventHandler $eventHandler;
    private readonly Language $language;

    public function __construct(Language $language)
    {
        $this->eventHandler = EventHandler::getInstance();
        $this->language = $language;
    }

    public function __invoke(): void
    {
        $event = new PreloadPhrasesCollecting($this->language);
        $this->eventHandler->fire($event);

        // TODO: Do something with the collected phrases.
    }
}

<?php

namespace wcf\system\language\preload\command;

use Laminas\Diactoros\Stream;
use wcf\data\language\Language;
use wcf\system\event\EventHandler;
use wcf\system\language\preload\PreloadPhrase;
use wcf\system\language\preload\PreloadPhrasesCollecting;
use wcf\util\StringUtil;

/**
 * Rebuilds the phrase preload cache for the
 * requested language.
 *
 * @author Alexander Ebert
 * @copyright 2001-2022 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Language\Preload\Command
 * @since 6.0
 */
final class CachePreloadPhrases
{
    private readonly EventHandler $eventHandler;
    private readonly Language $language;

    public function __construct(Language $language)
    {
        $this->eventHandler = EventHandler::getInstance();
        $this->language = $language;
    }

    public function __invoke(): void
    {
        $event = new PreloadPhrasesCollecting($this->language);
        $this->eventHandler->fire($event);

        $file = new Stream(\WCF_DIR . $this->language->getPreloadCacheFilename(), 'wb');
        foreach ($event->getPhrases() as $phrase) {
            $file->write(
                \sprintf(
                    "WoltLabLanguage.registerPhrase('%s', '%s');\n",
                    $phrase->name,
                    $this->getEncodedValue($phrase),
                )
            );
        }
        $file->close();
    }

    private function getEncodedValue(PreloadPhrase $phrase): string
    {
        if ($phrase->literal) {
            $value = $this->language->getDynamicVariable($phrase->name);
        } else {
            $value = $this->language->get($phrase->name);
        }

        return StringUtil::encodeJS($value);
    }
}

Create the preload cache for phrases

Create the preload cache for phrases


<?php

namespace Berti;

use Github;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\Process\Process;

function github_markdown_renderer(
    Github\Client $client,
    callable $repositoryDetector,
    SplFileInfo $document
): string
{
    return $client->api('markdown')->render(
        $document->getContents(),
        'markdown',
        $repositoryDetector($document) ?: null
    );
}

function github_repository_detector(SplFileInfo $document): string
{
    $cwd = $document->getRealPath();

    if (!$document->isDir()) {
        $cwd = dirname($cwd);
    }

    $process = new Process('git remote -v', $cwd);
    $process->run();

    $output = $process->getOutput();

    foreach (explode("\n", $output) as $line) {
        if (false === stripos($line, 'github.com')) {
            continue;
        }

        list(, $second) = explode("\t", $line, 2);
        list($url) = explode(' ', $second, 2);
        $url = str_replace('git@', '', $url);
        $parts = parse_url($url);

        return substr($parts['path'], 0, -4);
    }

    return '';
}

<?php

namespace Berti;

use Github;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\Process\Process;

function github_markdown_renderer(
    Github\Client $client,
    callable $repositoryDetector,
    SplFileInfo $document
): string
{
    return $client->api('markdown')->render(
        $document->getContents(),
        'markdown',
        $repositoryDetector($document) ?: null
    );
}

function github_repository_detector(SplFileInfo $document): string
{
    $cwd = $document->getRealPath();

    if (!$document->isDir()) {
        $cwd = dirname($cwd);
    }

    $process = new Process('git remote -v', $cwd);
    $process->run();

    $output = $process->getOutput();

    foreach (explode("\n", $output) as $line) {
        if (false === stripos($line, 'github.com')) {
            continue;
        }

        list(, $second) = explode("\t", $line, 2);
        list($url) = explode(' ', $second, 2);
        $url = str_replace('git@', '', $url);
        $parts = parse_url($url);

        $path = trim($parts['path'], '/');

        if ('.git' === substr($path, -4)) {
            $path = substr($path, 0, -4);
        }

        return $path;
    }

    return '';
}

Fix repo detection for https urls

Fix repo detection for https urls


<?php

namespace App\View;

class Helper extends \PHPixie\View\Helper
{

    public function has_active_page(\PHPixie\Request $request, $controller, $action = null, $append = false)
    {
        $controllerName = $request->param('controller');
        $actionName     = $request->param('action');

        if (($controller == $controllerName && empty($action)) ||
            ($controller == $controllerName && $action == $actionName)
        ) {
            echo(!$append ? 'class="active"' : 'active');
        }
    }

    public function has_smstools_var($name)
    {
        $config = $this->pixie->config->get('smstools3.config');
        return (isset($config[$name]) && !empty($config[$name]));
    }

    public function date_format($timestamp, $format = 'd-m-Y H:m:i')
    {
        return (date($format, $timestamp));
    }

}

<?php

namespace App\View;

class Helper extends \PHPixie\View\Helper
{

    public function has_active_page(\PHPixie\Request $request, $controller, $action = null, $append = false)
    {
        $controllerName = $request->param('controller');
        $actionName     = $request->param('action');

        if (($controller == $controllerName && empty($action)) ||
            ($controller == $controllerName && $action == $actionName)
        ) {
            echo(!$append ? 'class="active"' : 'active');
        }
    }

    public function has_smstools_var($name)
    {
        $config = $this->pixie->config->get('smstools3.config');
        return (isset($config[$name]) && !empty($config[$name]));
    }

    public function date_format($timestamp, $format = 'd-m-Y H:i:s')
    {
        return (date($format, $timestamp));
    }

}

Fix bug in date format

Fix bug in date format


<?php
class base {
	public $main;
	protected $__requirements = [];
	public $author = "Danny Morabito";
	public $version = "1.0.0";

	function __construct(&$main) {
		$this->main = &$main;
	}

	function getAuthor() {
		return $this->author;
	}

	function getVersion() {
		if(count(explode(".", $this->version)) != 3 && substr($this->version, -1) != "b")
			$this->version .= ".0";
		return $this->version;
	}
    function returnMe() {
        return $this;
    }

	function __destruct() {

	}
}

<?php
class base {
    public $main;
	protected $__requirements = [];
	public $author = "Danny Morabito";
	public $version = "1.0.0";
	public $edits = [];

	function __construct(&$main) {
		$this->main = &$main;
	}

	function getAuthor() {
		return $this->author;
	}

	function getVersion() {
		if(count(explode(".", $this->version)) != 3 && substr($this->version, -1) != "b")
			$this->version .= ".0";
		return $this->version;
	}
	function returnMe() {
		return $this;
	}
	function getEdits() {
		return $this->edits;
	}

	function __destruct() {

	}
}

Add edits array and getEdits() functions to all plugins


@extends('layout')

@section('title')File - {{$file}}@stop

@section('content')
    <h1>{{SourceController::linkedPath($path)}}</h1>
    <?php
	    $source = file_get_contents(base_path() . "/query/" . $file . ".sql");
    	$geshi = new GeSHi($source, 'sql');
    	echo $geshi->parse_code();
    ?>

@stop

@extends('layout')

@section('title')File - {{$file}}@stop

@section('content')

{{SourceController::linkedPath($path)}}

Query

    <?php
	    $source = file_get_contents(base_path() . "/query/" . $file . ".sql");
    	$geshi = new GeSHi($source, 'sql');
    	echo $geshi->parse_code();
    ?>

Output

@stop

Add titles to file view

Add titles to file view


<?php
/**
 * COmanage Registry Changelog Provisioner Model
 *
 * Copyright (C) 2013 University Corporation for Advanced Internet Development, Inc.
 *
 * 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.
 *
 * @copyright     Copyright (C) 2013 University Corporation for Advanced Internet Development, Inc.
 * @link          http://www.internet2.edu/comanage COmanage Project
 * @package       registry-plugin
 * @since         COmanage Registry v0.8
 * @license       Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * @version       $Id$
 */

class ChangelogProvisioner extends AppModel {
  // Required by COmanage Plugins
  // To enable this plugin, change the plugin type to "provisioner"
  public $cmPluginType = "provisioner";

  // Expose Menu Items
  public $cmPluginMenus = array();

  // Document foreign keys
  public $cmPluginHasMany = array(
    "CoPerson" => array("CoChangelogProvisionerExport")
  );
}

<?php
/**
 * COmanage Registry Changelog Provisioner Model
 *
 * Copyright (C) 2013 University Corporation for Advanced Internet Development, Inc.
 *
 * 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.
 *
 * @copyright     Copyright (C) 2013 University Corporation for Advanced Internet Development, Inc.
 * @link          http://www.internet2.edu/comanage COmanage Project
 * @package       registry-plugin
 * @since         COmanage Registry v0.8
 * @license       Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * @version       $Id$
 */

class ChangelogProvisioner extends AppModel {
  // Required by COmanage Plugins
  // To enable this plugin, change the plugin type to "provisioner"
  public $cmPluginType = "disabled-provisioner";

  // Expose Menu Items
  public $cmPluginMenus = array();

  // Document foreign keys
  public $cmPluginHasMany = array(
    "CoPerson" => array("CoChangelogProvisionerExport")
  );
}

Undo enabling of changelog provisioner

Undo enabling of changelog provisioner


<?php

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

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

/*
 * Sylius front controller.
 * Live (production) environment.
 */

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

//$loader = new ApcClassLoader('sylius', $loader);
//$loader->register(true);

require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
//$kernel = new AppCache($kernel);

$request = Request::createFromGlobals();

Request::enableHttpMethodParameterOverride();

$response = $kernel->handle($request);
$response->send();

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

<?php

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

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

/*
 * Sylius front controller.
 * Live (production) environment.
 */

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

//$loader = new ApcClassLoader('sylius', $loader);
//$loader->register(true);

require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', true);
//$kernel = new AppCache($kernel);

$request = Request::createFromGlobals();

Request::enableHttpMethodParameterOverride();

$response = $kernel->handle($request);
$response->send();

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

Install Env Production of project Sylius


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class API_Model extends CI_Model{

	function __construct(){
		parent::__construct();
	}

	function get_available_apis(){
		$this->db->select('api_id,name,description')
			->from('available_apis')
			->order_by('name');
		$query = $this->db->get();

		return $query->result();
	}

	function get_api_info($api_id){
		$this->db->select('name,logo,model_file')
			->from('available_apis')
			->where('api_id', $api_id);
		$query = $this->db->get();

		return $query->num_rows() === 1 ? $query->row() : NULL;
	}
}

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class API_Model extends CI_Model{

	function __construct(){
		parent::__construct();
	}

	function get_available_apis(){
		$this->db->select('api_id,name,description')
			->from('available_apis')
			->where('siteType', 'live')
			->order_by('name');
		$query = $this->db->get();

		return $query->result();
	}

	function get_api_info($api_id){
		$this->db->select('name,logo,model_file')
			->from('available_apis')
			->where('api_id', $api_id);
		$query = $this->db->get();

		return $query->num_rows() === 1 ? $query->row() : NULL;
	}
}

Make sure the main site only shows "live" APIs

With the creation of the beta site, make sure the main page
only shows those APIs that are *not* beta and are ready
for production use


<?php

namespace fennecweb\ajax\details;

use \fennecweb\WebService as WebService;

class TraitsOfOrganismsTest extends \PHPUnit_Framework_TestCase
{

    public function testExecute()
    {
        //Test if the traits to a selection of organisms is returned correctly
        list($service) = WebService::factory('details/TraitsOfOrganisms');
        $organism_ids = ['13','21','17'];
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'organism_ids' => $organism_ids)));
        $expected = ['habitat','elevation','plant growth habit','geographic distribution'];
        $this->assertEquals($expected, $results);
    }
}

<?php

namespace fennecweb\ajax\details;

use \fennecweb\WebService as WebService;

class TraitsOfOrganismsTest extends \PHPUnit_Framework_TestCase
{

    public function testExecute()
    {
        //Test if the traits to a selection of organisms is returned correctly
        list($service) = WebService::factory('details/TraitsOfOrganisms');
        $organism_ids = ['13','21','17'];
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'organism_ids' => $organism_ids)));
        $expected = [1 => 'habitat', 5 => 'elevation', 7 => 'plant growth habitat'];
        $this->assertEquals($expected, $results);
    }
}

Update expectation of still failing test case


<?php

/**
*
*/
class Test_News_MyTest extends UnitTestCase
{

    public function testTest()    {
        $this->assertTrue(false);
    }
}

<?php

/**
*
*/
OC_App::loadApp('news');
class Test_News_MyTest extends UnitTestCase
{

    public function testTest()    {
        $this->assertTrue(false);
    }
}

Add loadApp to test cases

Add loadApp to test cases


<?php

namespace NagParser\Definitions;

abstract class Definition
{
    private $type;

    private $config;

    public function __construct($type, $config)
    {
        $this->type = $type;
        $this->parseConfig($config);
    }

    private function parseConfig($config)
    {
        preg_match_all('/^\s*(.+?)\s+(.+)$/m', $config, $matches);
        $this->config = array_combine($matches[1], $matches[2]);
    }

    public function getOption($option)
    {
        if (array_key_exists($option, $this->config)) {
            return $this->config[$option];
        }
    }

    /**
     * @return mixed
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @return mixed
     */
    public function getType()
    {
        return $this->type;
    }

}

<?php

namespace NagParser\Definitions;

abstract class Definition
{
    private $type;

    private $config;

    public function __construct($type, $config)
    {
        $this->type = $type;
        $this->parseConfig($config);
    }

    private function parseConfig($config)
    {
        preg_match_all('/^\s*(.+?)\s+(.+)$/m', $config, $matches);
		$matches[2] = array_map('trim', $matches[2]);
        $this->config = array_combine($matches[1], $matches[2]);
    }

    public function getOption($option)
    {
        if (array_key_exists($option, $this->config)) {
            return $this->config[$option];
        }
    }

    /**
     * @return mixed
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @return mixed
     */
    public function getType()
    {
        return $this->type;
    }

}

Apply a trim to every value

Apply a trim to every value

this removes non-unix-style-newlines, spaces at the end of the line. To remove spaces at the end of the line is especially important, when you rely on the hostname as an example.


<?php defined('SYSPATH') or die('No direct script access.');
// Notify module view for Twitter Bootstrap 2.0
foreach ($msgs as $msg_type => $msgs_of_type):
    $class = NULL;
    if (in_array($msg_type, array('success', 'warning', 'info', 'error'))) {
        $class = ' alert-' . $msg_type;
    }?>
<div class="alert alert-block fade in<?=$class ?>">
    ×
    <?=count($msgs_of_type) ? implode("
\n", $msgs_of_type) : $msgs_of_type?>

<? endforeach ?>

<?php defined('SYSPATH') or die('No direct script access.');
// Notify module view for Twitter Bootstrap 2.0
foreach ($msgs as $msg_type => $msgs_of_type):
    $class = NULL;
    if (in_array($msg_type, array('success', 'warning', 'info', 'error')))
    {
        $class = ' alert-' . $msg_type;
    }?>
<div class="alert alert-block fade in<?php echo $class ?>">
    ×
    <?php echo count($msgs_of_type) ? implode("
\n", $msgs_of_type) : $msgs_of_type?>

<? endforeach ?>

Fix indention, php short open tags, braces


<?php

namespace Aguimaraes\Tests;

use Aguimaraes\Adapter\Redis;
use PHPUnit\Framework\TestCase;

class RedisTest extends TestCase
{
    public function testErrorCountHandling()
    {
        $v = 40;
        $redis = new Redis($this->mockErrorCountClient($v), 'test-prefix');
        $redis->setErrorCount('test-service', $v);

        $this->assertEquals($v, $redis->getErrorCount('test-service'));
    }

    private function mockErrorCountClient(int $v)
    {
        $stub = $this->createMock(\Predis\ClientInterface::class);
        $stub->expects($this->exactly(3))
            ->method('__call')
            ->withConsecutive(
                ['set', ['test-prefix.test-service.error_count', $v]],
                ['exists', ['test-prefix.test-service.error_count']],
                ['get', ['test-prefix.test-service.error_count']]
            )->will($this->onConsecutiveCalls(null, true, $v));

        return $stub;
    }
}

<?php

namespace Aguimaraes\Adapter;

use Aguimaraes\Adapter\Redis;
use PHPUnit\Framework\TestCase;

class RedisTest extends TestCase
{
    public function testErrorCountHandling()
    {
        $v = 40;
        $redis = new Redis($this->mockErrorCountClient($v), 'test-prefix');
        $redis->setErrorCount('test-service', $v);

        $this->assertEquals($v, $redis->getErrorCount('test-service'));
    }

    public function testLastCheck()
    {
        $redis = new Redis($this->mockLastCheckClient(), 'test-prefix');
        $time = $redis->updateLastCheck('another-test-service');

        $this->assertEquals($time, $redis->getLastCheck('another-test-service'));
    }

    private function mockErrorCountClient(int $v)
    {
        $stub = $this->createMock(\Predis\ClientInterface::class);
        $stub->expects($this->exactly(3))
            ->method('__call')
            ->withConsecutive(
                ['set', ['test-prefix.test-service.error_count', $v]],
                ['exists', ['test-prefix.test-service.error_count']],
                ['get', ['test-prefix.test-service.error_count']]
            )->will($this->onConsecutiveCalls(null, true, $v));

        return $stub;
    }

    private function mockLastCheckClient()
    {
        $stub = $this->createMock(\Predis\ClientInterface::class);
        $stub->expects($this->exactly(3))
            ->method('__call')
            ->withConsecutive(
                ['set', ['test-prefix.another-test-service.last_check', 99]],
                ['exists', ['test-prefix.another-test-service.last_check']],
                ['get', ['test-prefix.another-test-service.last_check']]
            )->will($this->onConsecutiveCalls(null, true));

        return $stub;
    }
}

function time() {
    return 99;
}

Add more tests to the redis adapter

Add more tests to the redis adapter