text
stringlengths 2
104M
| meta
dict |
---|---|
<?php
namespace Rehike\Model\Appbar;
use Rehike\i18n;
use Rehike\Model\Guide\MGuide;
class MAppbar
{
public $nav;
public $guide;
public $guideNotificationStrings;
/**
* Add a centre navigation section to the appbar.
*
* @return void
*/
public function addNav()
{
$this->nav = new MAppbarNav();
}
/**
* Add a guide response to the appbar.
*
* @param MGuide $guide
* @return void
*/
public function addGuide($guide)
{
$this->guide = $guide;
$this->guideNotificationStrings =
i18n::getNamespace("main/guide")->notifications
;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Clickcard;
use Rehike\Model\Common\MAbstractClickcard;
use Rehike\TemplateFunctions;
use Rehike\Model\Common\MButton;
/**
* Implements a common model for the signin clickcard.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
class MSigninClickcard extends MAbstractClickcard
{
public $template = "signin_clickcard";
public $class = "signin-clickcard";
public function __construct($heading, $message, $button)
{
$this->content = (object)[
"heading" => $heading,
"message" => $message,
"button" => new MButton([
"style" => "STYLE_PRIMARY",
"class" => ["signin-button"],
"navigationEndpoint" => (object) [
"commandMetadata" => (object) [
"webCommandMetadata" => (object) [
"url" => $button["href"] ?? ""
]
]
],
"text" => (object) [
"simpleText" => $button["text"] ?? ""
]
])
];
}
public static function fromData($data) {
$heading = $data->title ?? null;
$message = $data->content ?? null;
$button = $data->button->buttonRenderer ?? null;
return new self(
TemplateFunctions::getText($heading) ?? null,
TemplateFunctions::getText($message) ?? null,
[
"text" => TemplateFunctions::getText($button->text) ?? null,
"href" => TemplateFunctions::getUrl($button) ?? null
]
);
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels;
use Rehike\Model\Channels\Channels4\MChannelAboutMetadata;
use Rehike\Model\Channels\Channels4\BrandedPageV2\MSubnav;
use Rehike\Model\Channels\Channels4\Sidebar\MRelatedChannels;
use Rehike\Model\Browse\InnertubeBrowseConverter;
use Rehike\Model\Channels\Channels4\MSubConfirmationDialog;
use Rehike\Model\Common\MAlert;
use Rehike\Util\Base64Url;
use Rehike\Util\ParsingUtils;
use Rehike\i18n;
use Com\Youtube\Innertube\Helpers\VideosContinuationWrapper;
class Channels4Model
{
private static $baseUrl;
private static string $currentTab = "featured";
public static $yt;
private static int $videosSort;
private static $subscriptionCount = "";
/** @var string[] */
public static array $extraVideoTabs = [];
private static ?object $currentTabContents = null;
public static function bake(&$yt, $data, $sidebarData = null, $ownerData = null)
{
$i18n = i18n::getNamespace("channels");
self::$yt = &$yt;
self::$videosSort = $yt->videosSort ?? 0;
// Declare the response array.
$response = [];
if ($header = @$data->header->c4TabbedHeaderRenderer)
{
$response += ["header" => new Channels4\MHeader($header, self::getBaseUrl())];
}
elseif ($header = @$data->header->carouselHeaderRenderer)
{
$response += ["header" => new Channels4\MCarouselHeader($header, self::getBaseUrl())];
}
if (isset($response["header"]) && isset($data->contents->twoColumnBrowseResultsRenderer->tabs))
{
// Init appbar
$yt->appbar->addNav();
// Also add the owner info we just got to the appbar
$yt->appbar->nav->addOwner(
$response["header"]->getTitle(),
self::getBaseUrl(),
$response["header"]->thumbnail ?? "",
);
}
if ($alerts = @$data->alerts)
{
$response += ["alerts" => []];
foreach ($alerts as $alert)
{
$alert = $alert->alertWithButtonRenderer
?? $alert->alertRenderer
?? null;
if (
ParsingUtils::getText($alert->text) == $i18n->nonexistent
&& isset($response["header"])
)
{
$response["header"]->nonexistentMessage =
ParsingUtils::getText($alert->text);
}
else
{
$response["alerts"][] = MAlert::fromData($alert, [
"forceCloseButton" => true
]);
}
}
}
// If we have a header, do some header specific stuff.
if (isset($response["header"]))
{
// If we have twoColumnBrowseResultsRenderer with tabs,
// process them (add navigation and store a reference)
if ($tabsR = @$data->contents->twoColumnBrowseResultsRenderer->tabs)
{
self::processAndAddTabs($yt, $tabsR, $response["header"]);
}
$response += [
"title" => $response["header"]->getTitle()
];
// Also global subscription count for about
self::$subscriptionCount = $response["header"]->getSubscriptionCount();
}
if (!is_null($ownerData))
{
$response["secondaryHeader"] = new Channels4\MSecondaryHeader($ownerData);
}
// If we have a sidebar, go through it
if ($sidebarShelves = @$sidebarData->contents->twoColumnBrowseResultsRenderer->tabs[0]
->tabRenderer->content->sectionListRenderer->contents)
{
$featuredData = null;
if ("featured" == self::$currentTab)
{
$featuredData = &$data->contents->twoColumnBrowseResultsRenderer->tabs[0]
->tabRenderer->content->sectionListRenderer->contents
;
}
$sidebarData = self::getSidebarData($sidebarShelves, $featuredData);
if ($sidebarData)
{
self::initSecondaryColumn($response);
$response["secondaryContent"]->items = $sidebarData;
}
}
if (@$yt->subConfirmation && !is_null($response["header"]->title))
{
$response += ["subConfirmationDialog" => new MSubConfirmationDialog($response["header"])];
}
if (!is_null(self::$currentTabContents))
{
$response += ["content" => self::getTabContents(self::$currentTabContents)];
}
$response += ["baseUrl" => self::$baseUrl];
// Send the response array
return (object)$response;
}
/**
* Process channel tabs and add them to the header.
*
* @param object $yt Global state variable.
* @param object[] $tabs Array of tabs to process and add.
* @param MHeader $header Header to add the tabs to.
*/
public static function processAndAddTabs(object &$yt, array $tabs, Channels4\MHeader &$header): void
{
/** @var object */
$videosTab = null;
// Splice "live" tab as this should be cascaded into videos.
for ($i = 0; $i < count($tabs); $i++)
{
if (isset($tabs[$i]->tabRenderer))
{
// Do NOT call this $tab. It will break the logic for
// god only fucking knows why and you'll get some sorta
// duplicate tab renderer.
$tabR = &$tabs[$i];
$tabEndpoint = $tabR->tabRenderer->endpoint->commandMetadata->webCommandMetadata->url ?? null;
if (!is_null($tabEndpoint))
{
if (stripos($tabEndpoint, "/videos"))
{
$videosTab = &$tabR;
}
else if (stripos($tabEndpoint, "/streams") || stripos($tabEndpoint, "/shorts"))
{
self::$extraVideoTabs[] = substr($tabEndpoint, strrpos($tabEndpoint, "/") + 1);
$tabR->hidden = true;
if (@$tabR->tabRenderer->selected) $videosTab->tabRenderer->selected = true;
}
}
}
}
$header->addTabs($tabs, ($yt->partiallySelectTabs ?? false));
foreach ($tabs as $tab) if (@$tab->tabRenderer)
{
$tabEndpoint = $tab->tabRenderer->endpoint->commandMetadata->webCommandMetadata->url ?? null;
if (!is_null($tabEndpoint))
{
if (!@$tab->hidden && isset($yt->appbar->nav))
{
$yt->appbar->nav->addItem(
$tab->tabRenderer->title,
$tabEndpoint,
@$tab->tabRenderer->status
);
}
}
if (@$tab->tabRenderer->status > 0
|| @$tab->tabRenderer->selected)
{
self::$currentTabContents = &$tab->tabRenderer->content;
}
}
elseif (@$tab->expandableTabRenderer)
{
if (@$tab->expandableTabRenderer->selected) {
self::$currentTabContents = &$tab->expandableTabRenderer->content;
}
}
if (isset($yt->appbar->nav->items[0]))
{
$yt->appbar->nav->items[0]->title = $header->getTitle();
}
}
public static function initSecondaryColumn(&$response)
{
if (!isset($response["secondaryContent"]))
{
$response += [
"secondaryContent" => (object)[
"items" => []
]
];
}
}
public static function getTabContents($content)
{
if (isset($content->sectionListRenderer->contents[0]->itemSectionRenderer->contents[0]->channelAboutFullMetadataRenderer))
{
return (object)[
"channelAboutMetadataRenderer" =>
new MChannelAboutMetadata(
self::$subscriptionCount,
$content->sectionListRenderer->contents[0]->itemSectionRenderer->contents[0]->channelAboutFullMetadataRenderer
)
];
}
else if ($a = @$content->sectionListRenderer->contents[0]->itemSectionRenderer->contents[0]->gridRenderer)
{
return self::handleGridTab($a, $content);
}
else if ($a = @$content->richGridRenderer)
{
return self::handleGridTab(InnertubeBrowseConverter::richGridRenderer($a), $content, true);
}
else if (($a = @$content->sectionListRenderer->contents[0]->itemSectionRenderer) && (isset($a->contents[0]->backstagePostThreadRenderer)))
{
return self::handleBackstage($a);
}
else if ($a = @$content->sectionListRenderer)
{
if ($submenu = @$a->subMenu->channelSubMenuRenderer)
{
$brandedPageV2SubnavRenderer = MSubnav::fromData($submenu);
unset($a->subMenu);
}
return (object) [
"sectionListRenderer" => InnertubeBrowseConverter::sectionListRenderer($a, [
"channelRendererUnbrandedSubscribeButton" => true
]),
"brandedPageV2SubnavRenderer" => $brandedPageV2SubnavRenderer ?? null
];
}
else
{
return $content;
}
}
public static function handleGridTab($data, $parentTab, $rich = false)
{
$response = [];
switch (self::$currentTab)
{
case "videos":
case "streams":
case "shorts":
if ($rich)
{
$response += [
"brandedPageV2SubnavRenderer" => MSubnav::bakeVideos()
];
}
break;
default:
if ($subnav = @$parentTab->sectionListRenderer->subMenu->channelSubMenuRenderer)
{
$subnav = $subnav ?? null;
$response += [
"brandedPageV2SubnavRenderer" => MSubnav::fromData($subnav)
];
}
}
if ($rich && @$_GET["flow"] == "list")
{
if (isset($data->items[count($data->items) - 1]->continuationItemRenderer))
{
$token = &$data->items[count($data->items) - 1]->continuationItemRenderer->continuationEndpoint->continuationCommand->token;
$contWrapper = new VideosContinuationWrapper();
$contWrapper->setContinuation(
$token
);
$contWrapper->setList(true);
$token = Base64Url::encode($contWrapper->serializeToString());
}
$response += [
"items" => InnertubeBrowseConverter::generalLockupConverter($data->items, [
"listView" => true
])
];
}
else
{
$response += [
"browseContentGridRenderer" => InnertubeBrowseConverter::gridRenderer($data, [
"channelRendererUnbrandedSubscribeButton" => true
])
];
}
return (object)$response;
}
public static function handleBackstage($data)
{
$response = [
"backstageRenderer" => [
"comments" => (object)[
"commentThreads" => []
]
]
];
foreach ($data->contents as $item)
{
$content = $item->backstagePostThreadRenderer->post->backstagePostRenderer;
$response["backstageRenderer"]["comments"]->commentThreads[] = (object)[
"commentThreadRenderer" => (object)["commentRenderer" => $content]
];
}
return (object)$response;
}
public static function getSidebarData($shelves, &$featuredData)
{
$channelsShelves = [];
// Find the first channel shelf
foreach ($shelves as $i => $shelf)
{
$shelf = @$shelf->itemSectionRenderer->contents[0]
->shelfRenderer;
if ($channelItem = @$shelf->content->horizontalListRenderer
->items[0]->gridChannelRenderer
||
$channelItem = @$shelf->content->expandedShelfContentsRenderer
->items[0]->channelRenderer
)
{
$channelsShelves[] = $shelf;
if (null != $featuredData)
{
//array_splice($featuredData, $i, 1);
unset($featuredData[$i]);
}
}
}
if (0 < count($channelsShelves))
{
$shelves = [];
foreach ($channelsShelves as $shelf) {
$shelves[] = (object) [
"relatedChannelsRenderer" =>
MRelatedChannels::fromShelf($shelf)
];
}
return $shelves;
}
return null;
}
public static function registerCurrentTab(string $currentTab): void
{
self::$currentTab = $currentTab;
}
public static function getCurrentTab()
{
return self::$currentTab;
}
public static function registerBaseUrl($baseUrl)
{
self::$baseUrl = $baseUrl;
}
public static function getBaseUrl()
{
return self::$baseUrl;
}
public static function getVideosSort() {
return self::$videosSort;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4;
use Rehike\Model\Appbar\MAppbarNav;
use Rehike\Model\Appbar\MAppbarNavItem;
use Rehike\Util\ExtractUtils;
use Rehike\Util\ImageUtils;
use Rehike\TemplateFunctions as TF;
use Rehike\Model\Common\Subscription\MSubscriptionActions;
class MHeader
{
public $title;
public $badges;
public $thumbnail;
public $url;
public $banner;
public $headerLinks;
public $tabs;
public $subscriptionButton;
public $nonexistentMessage;
protected $subscriptionCount;
public function __construct($header, $baseUrl)
{
// Add the title if it exists
if ($a = @$header->title)
{
$this->title = (object)[
"text" => $a,
"href" => $baseUrl
];
}
// Add the avatar if it exists
if ($a = @$header->avatar)
{
$this->thumbnail = ImageUtils::changeSize($a->thumbnails[0]->url, 100);
}
$this->url = $baseUrl;
// Add the banner if it exists
if ($a = @$header->banner)
{
$this->banner = (object) [
"image" => $a->thumbnails[0] ->url ?? null,
"hdImage" => $a->thumbnails[3] ->url ?? null
];
$this->banner->isCustom = true;
}
else
{
$this->banner = new MDefaultBanner();
$this->banner->isCustom = false;
}
// Add the banner links if they exist.
if ($a = @$header->headerLinks->channelHeaderLinksRenderer)
$this->headerLinks = self::getHeaderLinks($a);
// Add the badges
if ($a = @$header->badges)
$this->badges = $a;
$count = "";
// Add the subscription button
if ($a = @$header->subscribeButton->subscribeButtonRenderer)
{
if (isset($header->subscriberCountText))
{
$count = ExtractUtils::isolateSubCnt(TF::getText($header->subscriberCountText));
$this->subscriptionCount = TF::getText($header->subscriberCountText);
}
$this->subscriptionButton = MSubscriptionActions::fromData(
$a, $count
);
}
// Channel owner
elseif (isset($header->editChannelButtons))
{
if (isset($header->subscriberCountText))
{
$count = ExtractUtils::isolateSubCnt(TF::getText($header->subscriberCountText));
$this->subscriptionCount = TF::getText($header->subscriberCountText);
}
$this->subscriptionButton = MSubscriptionActions::buildMock(
$count
);
}
elseif (isset($header->subscribeButton))
{
if (isset($header->subscriberCountText))
{
$count = ExtractUtils::isolateSubCnt(TF::getText($header->subscriberCountText));
$this->subscriptionCount = TF::getText($header->subscriberCountText);
}
$this->subscriptionButton = MSubscriptionActions::signedOutStub($count);
}
}
public function addTabs($tabs, $partSelect = false)
{
$this->tabs = [];
foreach ($tabs as &$tab)
{
if (isset($tab->tabRenderer))
{
if (!isset($tab->tabRenderer->title))
{
continue;
}
if (@$tab->tabRenderer->selected)
{
$tab->tabRenderer->status = $partSelect ? MAppbarNavItem::StatusPartiallySelected : MAppbarNavItem::StatusSelected;
}
else
{
$tab->tabRenderer->status = MAppbarNavItem::StatusUnselected;
}
unset($tab->tabRenderer->selected);
}
if (!@$tab->hidden)
{
$this->tabs[] = $tab;
}
}
}
public function getTitle()
{
return isset($this->title->text) ? $this->title->text : "";
}
public function getThumbnail()
{
return $this->thumbnail;
}
public function getSubscriptionCount()
{
return $this->subscriptionCount ?? "";
}
/**
* Process the header links provided and add href
* properties to them.
*/
protected static function getHeaderLinks($headerLinks)
{
$response = $headerLinks;
if (isset($response->primaryLinks))
{
$response->primaryLinks[0]->href =
$response->primaryLinks[0]->navigationEndpoint->urlEndpoint->url
;
}
if (isset($response->secondaryLinks))
{
for ($i = 0, $j = count($response->secondaryLinks); $i < $j; $i++)
{
$response->secondaryLinks[$i]->href =
$response->secondaryLinks[$i]->navigationEndpoint->urlEndpoint->url
;
}
}
return $response;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4;
use Rehike\Util\ExtractUtils;
use Rehike\i18n;
use Rehike\TemplateFunctions as TF;
class MChannelAboutMetadata
{
public $subscriberCountText;
public $viewCountText;
public $joinedDateText;
public $descriptionLabel;
public $detailsLabel;
public $linksLabel;
public $description;
public $country;
public $countryLabel;
public $primaryLinks;
public function __construct($subCount, $data)
{
$regexs = &i18n::getNamespace("main/regex");
$miscStrings = &i18n::getNamespace("main/misc");
$this->subscriberCountText = self::getRichStat(
$subCount,
$regexs->subscriberCountIsolator
);
$viewCountText = $miscStrings->viewTextPlural("0");
if (isset($data->viewCountText))
$viewCountText = TF::getText(@$data->viewCountText);
$this->viewCountText = self::getRichStat(
$viewCountText,
$regexs->viewCountIsolator
);
$this->joinedDateText = TF::getText(@$data->joinedDateText);
if (isset($data->descriptionLabel))
$this->descriptionLabel = TF::getText($data->descriptionLabel);
if (isset($data->detailsLabel))
$this->detailsLabel = TF::getText($data->detailsLabel);
if (isset($data->primaryLinksLabel))
$this->linksLabel = TF::getText($data->primaryLinksLabel);
if (isset($data->description))
$this->description = $data->description;
if (isset($data->country))
$this->country = TF::getText($data->country);
if (isset($data->countryLabel))
$this->countryLabel = TF::getText($data->countryLabel);
if (isset($data->primaryLinks))
$this->primaryLinks = $data->primaryLinks;
}
public static function getRichStat($text, $isolator)
{
if ("" == $text) return;
$number = preg_replace(
str_replace("/g", "/", $isolator), "", $text
);
$string = str_replace($number, "<b>$number<b>", $text);
$string = explode("<b>", $string);
$response = (object)["runs" => []];
for ($i = 0; $i < count($string); $i++)
{
$response->runs[$i] = (object)[
"text" => $string[$i]
];
if ($number == $string[$i])
{
$response->runs[$i]->bold = true;
}
}
return $response;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4;
use Rehike\TemplateFunctions;
use Rehike\Util\ImageUtils;
use Rehike\Util\ExtractUtils;
use Rehike\Model\Common\Subscription\MSubscriptionActions;
/**
* Provides a header for the Music, Sports,
* and Gaming channels.
*/
class MCarouselHeader extends MHeader
{
public function __construct($data, $baseUrl)
{
foreach ($data->contents as $content)
{
if ($header = @$content->topicChannelDetailsRenderer)
{
if (isset($header->title))
{
$this->title = (object) [
"text" => TemplateFunctions::getText($header->title),
"href" => $baseUrl
];
}
$this->banner = new MDefaultBanner();
$this->url = $baseUrl;
if (isset($header->avatar))
{
$this->thumbnail = ImageUtils::changeSize($header->avatar->thumbnails[0]->url, 100);
}
if (isset($header->subscribeButton->subscribeButtonRenderer))
{
$count = ExtractUtils::isolateSubCnt(TemplateFunctions::getText($header->subtitle));
$this->subscriptionCount = TemplateFunctions::getText($header->subtitle);
$this->subscriptionButton = MSubscriptionActions::fromData(
$header->subscribeButton->subscribeButtonRenderer,
$count
);
}
}
}
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4;
use Rehike\i18n;
use Rehike\Model\Common\Subscription\MSubscriptionActions;
use Rehike\Model\Common\MButton;
class MSubConfirmationDialog
{
public string $header;
public string $displayName;
public string $avatar;
public MSubscriptionActions $subscribeButton;
public MButton $closeButton;
public function __construct(?MHeader $header)
{
$i18n = i18n::getNamespace("channels");
$this->header = $i18n->subscriptionConfirmationHeader;
$this->displayName = $header->title->text;
$this->avatar = $header->thumbnail;
$this->subscribeButton = $header->subscriptionButton;
$gi18n = i18n::getNamespace("main/global");
$this->closeButton = new MButton([
"size" => "SIZE_DEFAULT",
"style" => "STYLE_DEFAULT",
"onclick" => "return!1",
"attributes" => [
"action" => "close"
],
"class" => [
"yt-dialog-dismiss",
"yt-dialog-close"
],
"text" => (object) [
"simpleText" => $gi18n->close
]
]);
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4;
use Rehike\i18n;
use Rehike\Model\Channels\Channels4\SecondaryHeader\MSecondaryHeaderLink;
use Rehike\Signin\API as SignIn;
class MSecondaryHeader
{
/** @var MSecondaryHeaderLink[] */
public array $links = [];
public function __construct(object $data)
{
$i18n = i18n::getNamespace("channels");
$ucid = SignIn::getInfo()["ucid"];
if (isset($data->subscribers))
{
$this->links[] = new MSecondaryHeaderLink(
$i18n->secondaryHeaderSubs(number_format($data->subscribers)),
"//studio.youtube.com/channel/$ucid"
);
}
if (isset($data->views))
{
$this->links[] = new MSecondaryHeaderLink(
$i18n->secondaryHeaderViews(number_format($data->views)),
"//studio.youtube.com/channel/$ucid/analytics",
"analytics"
);
}
$this->links[] = new MSecondaryHeaderLink(
$i18n->secondaryHeaderManager,
"//studio.youtube.com/channel/$ucid/videos",
"vm"
);
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4;
use Rehike\TemplateFunctions as TF;
/**
* Implements the (very hacky) Channels4 default banner.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
class MDefaultBanner
{
public $image;
public $hdImage;
public $isCustom = false;
public function __construct()
{
$resources = include "includes/resource_constants.php";
$this->image = TF::imgPath(
"channels/c4/default_banner",
$resources
);
$this->hdImage = TF::imgPath(
"channels/c4/default_banner_hq",
$resources
);
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4\SecondaryHeader;
class MSecondaryHeaderLink
{
public function __construct(
public string $text,
public string $url,
public ?string $icon = null
) {}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4\Sidebar;
use Rehike\TemplateFunctions as TF;
use Rehike\Model\Browse\InnertubeBrowseConverter as Converter;
class MRelatedChannels
{
public $title = "";
public $items = [];
public $seeMoreButton;
public static function fromShelf($shelf)
{
$me = new self();
// Convert the shelf first
$shelf = Converter::shelfRenderer($shelf, [
"channelRendererNoMeta" => true,
"channelRendererUnbrandedSubscribeButton" => true,
"channelRendererNoSubscribeCount" => true
]);
if (isset($shelf->title))
{
$me->title = $shelf->title;
}
$items = $shelf->content->horizontalListRenderer->items
?? $shelf->content->expandedShelfContentsRenderer->items
?? null;
if (!is_null($items))
foreach ($items as $i => $item)
{
$me->items[] = $item->gridChannelRenderer
?? $item->channelRenderer
?? null;
// Break at the 10th item
if ($i >= 9)
{
$me->seeMoreButton = new MRelatedChannelsSeeMoreButton(
@$shelf->endpoint->commandMetadata->webCommandMetadata->url
);
break;
}
}
return $me;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4\Sidebar;
use Rehike\i18n;
class MRelatedChannelsSeeMoreButton
{
public $title;
public $href;
public function __construct($href)
{
$strings = &i18n::getNamespace("channels");
$this->title = $strings->seeAll;
$this->href = $href;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4\BrandedPageV2;
use Rehike\i18n;
use Rehike\Model\Channels\Channels4Model;
class MSubnav
{
public $rightButtons;
public $leftButtons;
public $title;
public $backButton;
public function addBackButton($href)
{
$this->backButton = new MSubnavBackButton($href);
}
public static function bakeVideos()
{
$i = new self();
$baseUrl = Channels4Model::getBaseUrl();
$i->addBackButton($baseUrl);
if (!is_null(Channels4Model::getVideosSort()))
{
$i->rightButtons[] = self::getSortButton(Channels4Model::getVideosSort());
}
$flow = $_GET["flow"] ?? "grid";
if (!in_array($flow, ["grid", "list"])) $flow = "grid";
$i->rightButtons[] = self::getFlowButton($flow);
// Process uploads view
self::getViewButton($i);
return $i;
}
public static function getViewButton(self &$instance): void
{
$i18n = &i18n::getNamespace("channels");
if (count(Channels4Model::$extraVideoTabs) == 0)
{
$instance->title = match(Channels4Model::getCurrentTab())
{
"videos" => $i18n->viewUploads,
"streams" => $i18n->viewLiveStreams,
"shorts" => $i18n->viewShorts
};
}
else
{
$baseUrl = Channels4Model::getBaseUrl();
\Rehike\ControllerV2\Core::$state->test = Channels4Model::$extraVideoTabs;
$options = [];
$uploadsText = $i18n->viewUploads;
$streamsText = $i18n->viewLiveStreams;
$shortsText = $i18n->viewShorts;
if ("streams" == Channels4Model::getCurrentTab())
{
$activeText = $streamsText;
$options += [$uploadsText => "$baseUrl/videos"];
if (in_array("shorts", Channels4Model::$extraVideoTabs))
{
$options += [$shortsText => "$baseUrl/shorts"];
}
}
else if ("shorts" == Channels4Model::getCurrentTab())
{
$activeText = $shortsText;
$options += [$uploadsText => "$baseUrl/videos"];
if (in_array("streams", Channels4Model::$extraVideoTabs))
{
$options += [$streamsText => "$baseUrl/streams"];
}
}
else
{
$activeText = $uploadsText;
if (in_array("streams", Channels4Model::$extraVideoTabs))
{
$options += [$streamsText => "$baseUrl/streams"];
}
if (in_array("shorts", Channels4Model::$extraVideoTabs))
{
$options += [$shortsText => "$baseUrl/shorts"];
}
}
$instance->leftButtons[] = new MSubnavMenuButton("view", $activeText, $options);
}
}
public static function getSortButton($sort) {
$i18n = i18n::getNamespace("channels");
$baseUrl = Channels4Model::getBaseUrl();
$tab = Channels4Model::getCurrentTab();
$flow = $_GET["flow"] ?? "grid";
$options = [];
$popularText = $i18n->videoSortPopular;
$newestText = $i18n->videoSortNewest;
$oldestText = $i18n->videoSortOldest;
switch ($sort)
{
case 0:
$activeText = $newestText;
$options += [
$popularText => "$baseUrl/$tab?sort=p&flow=$flow",
$oldestText => "$baseUrl/$tab?sort=da&flow=$flow"
];
break;
case 1:
$activeText = $popularText;
$options += [
$oldestText => "$baseUrl/$tab?sort=da&flow=$flow",
$newestText => "$baseUrl/$tab?sort=dd&flow=$flow"
];
break;
case 2:
$activeText = $oldestText;
$options += [
$popularText => "$baseUrl/$tab?sort=p&flow=$flow",
$newestText => "$baseUrl/$tab?sort=dd&flow=$flow"
];
break;
default:
return;
}
return new MSubnavMenuButton("sort", $activeText, $options);
}
public static function getFlowButton($view)
{
$i18n = &i18n::getNamespace("channels");
$baseUrl = Channels4Model::getBaseUrl();
$gridText = $i18n->flowGrid;
$listText = $i18n->flowList;
$sort = match (Channels4Model::getVideosSort()) {
0 => "dd",
1 => "p",
2 => "da",
default => "dd"
};
$tab = Channels4Model::getCurrentTab();
$options = [];
if ("grid" == $view)
{
$activeText = $gridText;
$options += [$listText => "$baseUrl/$tab?sort=$sort&flow=list"];
}
else if ("list" == $view)
{
$activeText = $listText;
$options += [$gridText => "$baseUrl/$tab?sort=$sort&flow=grid"];
}
return new MSubnavMenuButton("flow", $activeText, $options);
}
public static function fromData($data)
{
$i18n = &i18n::getNamespace("channels");
$baseUrl = Channels4Model::getBaseUrl();
$i = new self();
$i->addBackButton($baseUrl);
if (count($data->contentTypeSubMenuItems) > 1) {
$i->leftButtons[] = MSubnavMenuButton::fromData($data->contentTypeSubMenuItems);
} else {
$i->title = $data->contentTypeSubMenuItems[0]->title;
}
return $i;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4\BrandedPageV2;
class MSubnavBackButton
{
public $accessibilityLabel;
public $href;
public function __construct($href)
{
$this->accessibilityLabel = "Back";
$this->href = $href;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4\BrandedPageV2;
class MSubnavMenuButtonMenu
{
public $title;
public $href;
public function __construct($title, $href)
{
$this->title = $title;
$this->href = $href;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Channels\Channels4\BrandedPageV2;
class MSubnavMenuButton
{
public $title;
public $type;
public $items;
public function __construct($type, $title, $array = [])
{
$this->type = $type;
$this->title = $title;
foreach ($array as $title => $href)
{
$this->addMenu(new MSubnavMenuButtonMenu(
$title, $href
));
}
}
public function addMenu($menu)
{
$this->items[] = $menu;
}
public static function fromData($data) {
$items = [];
foreach ($data as $item) {
if ($item->selected) {
$title = $item->title;
} else {
$items[$item->title] = $item->endpoint->commandMetadata->webCommandMetadata->url;
}
}
return new self("view", $title, $items);
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\AddTo;
use Rehike\i18n;
class MAddTo
{
public $createNewText;
public $searchText;
public $playlists;
public $createPlaylistPanelRenderer;
public function __construct($lists)
{
$strs = i18n::getNamespace("addto");
$this->createNewText = $strs->createNewPlaylist;
$this->searchText = $strs->searchPlaylists;
$this->createPlaylistPanelRenderer = new MCreatePlaylist(true);
$this->playlists = $lists;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\AddTo;
use Rehike\i18n;
class MCreatePlaylist
{
public $label;
public $publicText;
public $unlistedText;
public $privateText;
public $playlistPrivacyText;
public $isCompact = false;
public function __construct($compact = false)
{
$strs = i18n::getNamespace("addto");
$this->label = $strs->playlistTitle;
$this->publicText = $strs->privacyPublic;
$this->unlistedText = $strs->privacyUnlisted;
$this->privateText = $strs->privacyPrivate;
$this->playlistPrivacyText = $strs->playlistPrivacy;
$this->isCompact = $compact;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Feed;
use Rehike\Model\Appbar\MAppbarNav;
use Rehike\i18n;
use Rehike\Signin\API as SignIn;
class MFeedAppbarNav extends MAppbarNav {
public function __construct($feedId) {
$i18n = i18n::newNamespace("feedappbar");
$i18n->registerFromFolder("i18n/appbar");
$this->addItem($i18n->tabHome, "/", $feedId == "FEwhat_to_watch" ? 2 : 0);
$this->addItem($i18n->tabTrending, "/feed/trending", $feedId == "FEtrending" ? 2 : 0);
if (SignIn::isSignedIn()) $this->addItem($i18n->tabSubscriptions, "/feed/subscriptions", $feedId == "FEsubscriptions" ? 2 : 0);
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Guide;
use Rehike\i18n;
use Rehike\Signin\API as Signin;
use Rehike\ConfigManager\ConfigManager;
use Rehike\Model\Common\MButton;
use Rehike\Model\Traits\NavigationEndpoint;
/**
* A god class for converting InnerTube guide responses to
* the Rehike format.
*
* It's messy because I was lazy and sick while writing this,
* sorry.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
class Converter
{
/**
* Since the entire purpose of this class is to convert from
* data, this is the insertion point function.
*
* It takes in a raw (but JSON decoded) YTI guide response and
* processes it into a Rehike format (which is mostly just reorganised
* to change the layout a little bit).
*
* @param object $data of the raw InnerTube response
* @return object[] array of the modified items.
*/
public static function fromData($data)
{
// Log the sign in state from the Signin service
// so that I can use it later.
$signedIn = Signin::isSignedIn();
$strings = &i18n::getNamespace("main/guide");
$response = [];
// Push the main section to the response
$response[] = self::getMainSection($data, $signedIn);
// If signed in,
// push the library and subscriptions sections,
// else
// push only the best of YouTube section
if ($signedIn)
{
$response[] = self::getLibrarySection($data);
$response[] = self::getSubscriptionSection($data);
}
else
{
$response[] = self::getBestOfYouTubeSection();
}
// Push the guide management items (the "end section")
$response[] = self::getEndSection($signedIn);
// Add sign in promo if not logged in
if (!$signedIn)
{
foreach ($data->items as $item)
foreach ($item as $key => $content)
if ("guideSigninPromoRenderer" == $key)
{
$response[] = $item;
}
}
return $response;
}
/**
* This function is responsible for getting the "main section" of the
* guide.
*
* This section should contain the following items:
*
* - Home
* - My channel [if logged in]
* - Trending
* - Subscriptions [if logged in]
* - History [only if logged out]
*
* @param object $data
* @param bool $signedIn
* @return object {guideSectionRenderer}
*/
public static function getMainSection($data, $signedIn = false)
{
$response = [];
// Some strings, like "My channel" and "Trending" aren't
// reported at all by InnerTube, so I have to use a custom
// language file to store these strings in.
$strings = &i18n::getNamespace("main/guide");
// Get signin info if possible (needed for the UCID)
$signinInfo = null;
// Casted to object in order to access in string interpolation
if ($signedIn)
$signinInfo = (object)Signin::getInfo();
$mainSection = $data->items[0]->guideSectionRenderer->items;
$homeItem = self::getItemByIcon($mainSection, "WHAT_TO_WATCH");
$subscriptionsItem = self::getItemByIcon($mainSection, "SUBSCRIPTIONS");
// Correct icon type for subscriptions icon
if (null != $subscriptionsItem)
{
$subscriptionsItem->guideEntryRenderer->icon->iconType = "MY_SUBSCRIPTIONS";
}
//
// Push the main section items to the response array
//
// Home item
$response[] = $homeItem;
// My channel item (if signed in)
if ($signedIn && isset($signinInfo->ucid) && @$signinInfo->ucid != "")
{
$response[] = self::bakeGuideItem(
"/channel/{$signinInfo->ucid}",
$strings->myChannel,
"SYSTEM::MY_CHANNEL"
);
}
// Trending item
$response[] = self::bakeGuideItem(
"/feed/trending", $strings->trending, "SYSTEM::TRENDING"
);
// Subscriptions item (if signed in)
if ($signedIn)
{
$response[] = $subscriptionsItem;
}
// History item (only if signed out)
if (!$signedIn)
{
$secondarySection = $data->items[1]->guideSectionRenderer->items;
$historyItem = self::getItemByIcon($secondarySection, "WATCH_HISTORY");
// Correct icon type
$historyItem->guideEntryRenderer->icon->iconType = "HISTORY";
$response[] = $historyItem;
}
// Response with a synthesised guideSectionRenderer wrapper.
return (object)[
"guideSectionRenderer" => (object)[
"items" => $response
]
];
}
/**
* This function is responsible for getting the Best of YouTube
* section.
*
* Best of YouTube used to be directly obtained from InnerTube,
* but as of late 2022, they've changed it in a way that makes
* it incompatible with Hitchhiker. Now, we build it entirely
* locally, including the images (which are in
* /rehike/static/best_of_youtube)
*/
public static function getBestOfYouTubeSection() {
$strings = i18n::getNamespace("main/guide");
// Thumbnail prefix and suffix
$format = ConfigManager::getConfigProp("appearance.oldBestOfYouTubeIcons")
? "/rehike/static/best_of_youtube/%s_old.jpg"
: "/rehike/static/best_of_youtube/%s.jpg";
$response = (object) [];
$response->formattedTitle = (object) [
"simpleText" => $strings->bestOfYouTubeTitle
];
$items = [];
$items[] = self::bakeGuideItem(
"/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ",
$strings->bestOfYouTubeMusic,
sprintf($format, "music")
);
$items[] = self::bakeGuideItem(
"/channel/UCEgdi0XIXXZ-qJOFPf4JSKw",
$strings->bestOfYouTubeSports,
sprintf($format, "sports")
);
$items[] = self::bakeGuideItem(
"/gaming",
$strings->bestOfYouTubeGaming,
sprintf($format, "gaming")
);
$items[] = self::bakeGuideItem(
"/channel/UClgRkhTL3_hImCAmdLfDE4g",
$strings->bestOfYouTubeMoviesTv,
sprintf($format, "movies_tv")
);
$items[] = self::bakeGuideItem(
"/channel/UCYfdidRxbB8Qhf0Nx7ioOYw",
$strings->bestOfYouTubeNews,
sprintf($format, "news")
);
$items[] = self::bakeGuideItem(
"/channel/UC4R8DWoMoI7CAwX8_LjQHig",
$strings->bestOfYouTubeLive,
sprintf($format, "live")
);
$items[] = self::bakeGuideItem(
"/channel/UCBR8-60-B28hp2BmDPdntcQ",
$strings->bestOfYouTubeSpotlight,
sprintf($format, "spotlight")
);
$items[] = self::bakeGuideItem(
"/channel/UCzuqhhs6NWbgTzMuM09WKDQ",
$strings->bestOfYouTube360,
sprintf($format, "360")
);
$response->items = $items;
return (object) [
"guideSectionRenderer" => $response
];
}
/**
* This function is responsible for getting the library section.
*
* It's a huge mess.
*
* This section is mostly taken raw from InnerTube, with some filters
* to skip past undesirable items. It should contain (in no specific order):
*
* - History
* - Watch later
* - Liked videos
* - <All user playlists>
*
* It only appears if logged in.
*
* @param object $data
* @return object {guideSectionRenderer}
*/
public static function getLibrarySection($data)
{
$mainSection = $data->items[0]->guideSectionRenderer->items;
// Custom strings are only used this time for the expander
// text.
$strings = &i18n::getNamespace("main/guide");
$ucid = Signin::getInfo()["ucid"];
// This atrocious pattern appears a lot here.
// It's just the easiest way to get the last item of the array.
if (isset($mainSection[count($mainSection) - 1]->guideCollapsibleSectionEntryRenderer))
{
$librarySection = $mainSection[count($mainSection) - 1]->guideCollapsibleSectionEntryRenderer;
}
else
{
return null;
}
// Store the title for later use (it needs to have a navigation endpoint later on)
$title = $librarySection->headerEntry->guideEntryRenderer->formattedTitle->simpleText;
$response = [];
/**
* A support types map.
*
* The left side is checked against, and then replaced with the
* content of the right side.
*
* This is only currently needed for the history icon type, but in case
* InnerTube changes the icon types later I just layed them all out
* here.
*
* @var string[]
*/
$supportedTypes = [
"WATCH_HISTORY" => "HISTORY",
"WATCH_LATER" => "WATCH_LATER",
"LIKES_PLAYLIST" => "LIKES_PLAYLIST",
"PLAYLISTS" => "PLAYLISTS"
];
// Count all items and add them if they're a supported type
// (also correct the icon types)
// Basically just make use of everything I did above!
foreach ($librarySection->sectionItems as $item)
{
// Skip non guide entry renderers
if (!isset($item->guideEntryRenderer)) continue;
$iconType = @$item->guideEntryRenderer->icon->iconType;
if (isset($supportedTypes[$iconType]))
{
$item->guideEntryRenderer->icon->iconType = $supportedTypes[$iconType];
$response[] = $item;
}
}
// Hack: move the official collapsible (too small for my taste)
// into the response body (very large) so that we can shrink it
// down to 4 (perfect)
if (isset($librarySection->sectionItems[count($librarySection->sectionItems) - 1]->guideCollapsibleEntryRenderer))
{
$c = $librarySection->sectionItems[count($librarySection->sectionItems) - 1]->guideCollapsibleEntryRenderer;
$response = array_merge($response, $c->expandableItems);
}
// Move overflow items to the show more container
// if needed
if (count($response) > 4)
{
$collapsible = [];
for ($i = 4; $i < count($response); $i++)
{
$collapsible[] = $response[$i];
}
// Remove the original items
array_splice($response, 4);
// Synthesise a little guide collapsible entry renderer
// for containing the excess items. This differs a little
// bit from the InnerTube specification.
$response[] = (object)[
"guideCollapsibleEntryRenderer" => (object)[
"expandableItems" => $collapsible,
"expanderItem" => (object)[
"text" => $strings->showMore
],
"collapserItem" => (object)[
"text" => $strings->showFewer
]
]
];
}
// Finally, synthesise the section renderer.
// The formatted title is an ugly bit of code to make the title
// also an anchor. This actually is according to the InnerTube spec.
return (object)[
"guideSectionRenderer" => (object)[
"formattedTitle" => (object)[
"runs" => [
(object)[
"text" => $title,
"navigationEndpoint" => (object)[
"commandMetadata" => (object)[
"webCommandMetadata" => (object)[
"url" => "/channel/$ucid/playlists"
]
]
]
]
]
],
"items" => $response
]
];
}
/**
* This function is responsible for getting the subscriptions section
* of the guide data.
*
* This is one of the most complicated parts of the guide, since it
* can refresh dynamically with user interactions across the site
* (i.e. subscribing to a channel).
*
* This is also taken directly from InnerTube, so watch out for any
* possible changes that may break it.
*
* It should contain all user subscriptions.
*
* @param object $data
* @return object {guideSubscriptionsSectionRenderer} (from InnerTube)
*/
public static function getSubscriptionSection($data)
{
// Find the subscription section index
foreach ($data->items as &$item)
foreach ($item as $key => &$contents)
{
if ("guideSubscriptionsSectionRenderer" == $key)
{
$section = &$contents;
$responseItem = &$item;
}
}
if (!isset($section)) return self::buildSubscriptionsPromoSection();
// Ugly last item hack to get rid of the "show more" button WEB v2
// reports
if (isset($section->items[count($section->items ?? []) - 1]->guideCollapsibleEntryRenderer))
{
$contents = $section->items[count($section->items) - 1]->guideCollapsibleEntryRenderer->expandableItems;
// Remove the item from the array so it doesn't cause any issues.
array_splice($section->items, count($section->items) - 1, 1);
// Then add all of its children back into the parent array (to flatten it)
$section->items = array_merge($section->items, $contents);
}
// Ditto: remove guide builder hack
if (isset($section->items[count($section->items) - 1]->guideEntryRenderer->icon))
{
array_splice($section->items, count($section->items) - 1, 1);
}
// Iterate all remaining and add counts if needed
foreach ($section->items as &$item)
{
$content = &$item->guideEntryRenderer;
// Live badge trumps count badge, but this check is done on the
// templater end. Both are reported otherwise.
// In addition, this may be reformed in the future to
// actually count the number of unwatched videos from a user's subscribed
// channels :O (when? how?)
if ("GUIDE_ENTRY_PRESENTATION_STYLE_NEW_CONTENT" == $content->presentationStyle)
{
if (!isset($content->badges)) $content->badges = (object)[];
// Hardcoded feed count since feeds no longer exist
// Hitchhiker also used the hardcoded value of 1
$content->badges->count = 1;
}
}
return $responseItem;
}
/**
* Build the subscription promo section.
* This shows when you have no subscriptions.
*/
public static function buildSubscriptionsPromoSection() {
$i18n = i18n::getNamespace("main/guide");
$response = (object) [];
$format = ConfigManager::getConfigProp("appearance.oldBestOfYouTubeIcons")
? "/rehike/static/best_of_youtube/%s_old.jpg"
: "/rehike/static/best_of_youtube/%s.jpg";
$response->formattedTitle = (object) [
"simpleText" => $i18n->subscriptions,
"navigationEndpoint" => NavigationEndpoint::createEndpoint("/feed/channels")
];
$response->button = new MButton([
"style" => "STYLE_PRIMARY",
"text" => (object) [
"simpleText" => $i18n->subscriptionsPromoButton
],
"icon" => (object) [
"iconType" => "PLUS"
],
"navigationEndpoint" => NavigationEndpoint::createEndpoint("/feed/guide_builder")
]);
$response->tooltip = (object) [
"text" => (object) [
"simpleText" => $i18n->subscriptionsPromoTooltip
],
"navigationEndpoint" => NavigationEndpoint::createEndpoint("/feed/guide_builder")
];
$response->items = [];
$response->items[] = self::bakeGuideItem(
"/channel/UCF0pVplsI8R5kcAqgtoRqoA",
$i18n->bestOfYouTubePopularOnYouTube,
sprintf($format, "popular_on_youtube")
);
$response->items[] = self::bakeGuideItem(
"/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ",
$i18n->bestOfYouTubeMusic,
sprintf($format, "music")
);
$response->items[] = self::bakeGuideItem(
"/channel/UCEgdi0XIXXZ-qJOFPf4JSKw",
$i18n->bestOfYouTubeSports,
sprintf($format, "sports")
);
$response->items[] = self::bakeGuideItem(
"/gaming",
$i18n->bestOfYouTubeGaming,
sprintf($format, "gaming")
);
return (object) [
"guideSubscriptionsPromoSectionRenderer" => $response
];
}
/**
* This function is responsible for getting the guide
* "end section".
*
* This section contains a few extra items related to subscription
* management.
*
* This section doesn't use any data from InnerTube at all, so it should
* be the sturdiest section in terms of long-term stability.
*
* This section should contain:
*
* - Browse channels
* - Manage subscriptions [if logged in]
*
* @param bool $signedIn
* @return object {guideSectionRenderer}
*/
public static function getEndSection($signedIn = false)
{
$response = [];
$strings = &i18n::getNamespace("main/guide");
// Bake "browse channels" (guide builder) item
$response[] = self::bakeGuideItem(
"/feed/guide_builder",
$strings->guideBuilderLabel,
"SYSTEM::BUILDER"
);
// Also, if signed in, add the "manage subscriptions" item
if ($signedIn)
{
$response[] = self::bakeGuideItem(
"/feed/channels",
$strings->manageSubscriptionsLabel,
"SYSTEM::SUBSCRIPTION_MANAGER"
);
}
// And return
return (object)[
"guideSectionRenderer" => (object)[
"items" => $response
]
];
}
/**
* This function is used to conveniently synthesise my own guide
* items.
*
* @param string $endpoint
* @param string $name
* @param string $icon (will be a thumbnail unless prefixed with SYSTEM::)
* @return object {guideEntryRenderer}
*/
public static function bakeGuideItem($endpoint, $name, $icon)
{
//
// Step 1: Determine the endpoint of the data and create a new
// item template containing the provided information.
// This entire section is object oriented programming at
// its finest!
//
/**
* Contains extra information about the endpoint that isn't just
* its command metadata.
*
* As you can guess, this was added particularly last minute, and
* particularly when I was just drifting off to sleep.
*
* As such, this implement is absolutely garbage. It's mostly used here
* to synthesise a browseEndpoint or urlEndpoint for encoding
* the guide's endpoint later on.
*
* @var string[] (but only by technicality, it will be casted to an object later)
*/
$extraEndpointInfo = [];
if (
"/feed" == substr($endpoint, 0, 5) ||
"/channel" == substr($endpoint, 0, 8) ||
"/c" == substr($endpoint, 0, 2) ||
"/user" == substr($endpoint, 0, 5) ||
"/playlist" == substr($endpoint, 0, 9)
)
{
// NO ASSOCIATIVE ARRAY?
$before = [
"/feed/",
"/channel/",
"/c/",
"/user/",
"/playlist?list="
];
// NO ASSOCIATIVE ARRAY?
$after = [
"FE",
"",
"",
"",
"PL"
];
// This needs to be a variable (not a literal) because it is
// a forced reference. Wtf php?
$wtfphp = 1;
$browseId = str_replace($before, $after, $endpoint, $wtfphp);
$extraEndpointInfo = [
"browseEndpoint" => (object)[
"browseId" => $browseId
]
];
}
else // The easier case
{
$extraEndpointInfo = [
"urlEndpoint" => (object)[
"url" => $endpoint
]
];
}
$item = (object)[
"navigationEndpoint" => (object)([
"commandMetadata" => (object)[
"webCommandMetadata" => (object)[
"url" => $endpoint
]
]
] + $extraEndpointInfo), // Merge this data with the extra info
"formattedTitle" => (object)[
"simpleText" => $name
]
];
//
// Step 2: Determine the icon type and add it to the item template.
//
if ("SYSTEM::" == substr($icon, 0, 8))
{
$icon = substr($icon, 8);
$item->icon = (object)[
"iconType" => $icon
];
}
else
{
$item->thumbnail = (object)[
"thumbnails" => [
(object)[
"url" => $icon
]
]
];
}
// Then just a standard return.
return (object)[
"guideEntryRenderer" => $item
];
}
/**
* This is a convenient helper function for crawling the InnerTube response.
*
* This allows me to search for a specific item by using its icon type, which
* is the most consistent variable for finding them.
*
* @param object[] $items array
* @param string $icon to search for
* @return object|null
*/
public static function getItemByIcon($items, $icon)
{
// Skip all non-guide-entry-renderers because I don't want them
// anyways
foreach ($items as $item) if ($content = @$item->guideEntryRenderer)
{
// Also skip items that don't have an icon type
if (!is_string(@$content->icon->iconType)) continue;
// strtolower for case insensitivity
if (strtolower($icon) == strtolower($content->icon->iconType))
return $item;
}
// Otherwise it doesn't exist
return null;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Guide;
/**
* Implements the guide model.
*
* This is a very barren class. Most of the functionality is implemented
* in the Converter.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
class MGuide
{
/**
* An array of all the guide items.
*
* @var object[]
*/
public $items;
/**
* Process an InnerTube response and create a standard
* guide response from it.
*
* @return void
*/
public static function fromData($data)
{
$me = new self();
$me->items = Converter::fromData($data);
return $me;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common;
/**
* Abstract clickcard definitions.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
abstract class MAbstractClickcard
{
public $template = "";
public $class = "";
public $content;
/**
* Should generate content only. Template and
* class should be overridden in the child class
* declaration.
*
* @return void
*/
public function __construct() {}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common;
/**
* Implements the common button model
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
#[\AllowDynamicProperties]
class MButton
{
public $style = "STYLE_DEFAULT";
public $size = "SIZE_DEFAULT";
public $icon;
public $tooltip;
public $class = [];
public $attributes = [];
public $accessibility;
public $isDisabled = false;
public function __construct($array = [])
{
$this->text = (object)["runs" => []];
foreach ($array as $key => $value)
{
$this->{$key} = $value;
}
}
protected function setText($string)
{
$this->text = (object)[
"runs" => [(object)[
"text" => $string
]]
];
}
protected function addRun($object)
{
$this->text->runs[] = $object;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common;
/**
* Implements a model for the common toggle button
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
class MToggleButton extends MButton
{
protected $hideNotToggled = false;
public $isToggled = false;
public function __construct($isToggled = false, $array = [])
{
parent::__construct();
$this->isToggled = $isToggled;
if ($this->hideNotToggled && !$isToggled)
{
$this->class[] = "hid";
}
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common;
use Rehike\Model\Common\MButton;
use Rehike\Util\ParsingUtils;
class MAlert {
const TypeInformation = "info";
const TypeWarning = "warn";
const TypeError = "error";
const TypeSuccess = "success";
/**
* What type the alert should be rendered in.
*/
public string $type = self::TypeInformation;
/**
* Text displayed inside the alert.
*/
public string $text = "";
/**
* Whether or not to render a close button
* on the right side of the alert.
*/
public bool $hasCloseButton = true;
/**
* Buttons to be shown on the right of the alert.
*
* @var MAlertButton[]
*/
public $buttons = [];
public function __construct($data) {
$this->type = $data["type"];
$this->text = $data["text"] ?? null;
$this->hasCloseButton = $data["hasCloseButton"] ?? true;
}
/**
* Build an alert from InnerTube data.
*
* @param object $data Data.
* @param array $flags Special flags.
* @return MAlert
*/
public static function fromData(object $data, array $flags = []): self {
return new self([
"type" => MAlert::parseInnerTubeType($data->type),
"hasCloseButton" => (isset($data->dismissButton) || @$flags["forceCloseButton"]),
"text" => ParsingUtils::getText($data->text)
]);
}
/**
* Parse the alert type format returned from InnerTube
*
* @param string $type Alert type returne from InnerTube.
*
* @return string
*/
public static function parseInnerTubeType($type) {
switch ($type) {
case "INFO":
return self::TypeInformation;
break;
case "WARNING":
return self::TypeWarning;
break;
case "ERROR":
return self::TypeError;
break;
case "SUCCESS":
return self::TypeSuccess;
break;
}
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common\Subscription;
use Rehike\Model\Common\MButton;
/**
* Implements a model for the subscription button.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
class MSubscriptionButton extends MButton
{
/** @var string */
public $style = "";
/** @var object */
public $icon;
/** @var string[] */
public $class = [
"yt-uix-subscription-button",
"yt-can-buffer"
];
/** @var string[] */
public $accessibility;
/** @var string[] */
public $attributes = [
"subscribed-timestamp" => "0",
"style-type" => "", // branded/unbranded
"clicktracking" => "",
"show-unsub-confirm-dialog" => "true",
"show-unsub-confirm-time-frame" => "always",
"channel-external-id" => ""
];
/** @var bool */
public $disabled;
/** @var bool */
public $subscribed;
/** @var bool */
public $branded;
/** @var string */
public $type;
public function __construct($opts)
{
parent::__construct([]);
// Default options
$opts += [
"isDisabled" => false,
"isSubscribed" => false,
"type" => "FREE",
"branded" => "true",
"channelExternalId" => "",
"params" => "",
"tooltip" => null
];
$this->icon = (object) [];
$this->accessibility = (object) [
"accessibilityData" => (object) [
"live" => "polite",
"busy" => "false"
]
];
$this->isDisabled = $opts["isDisabled"];
$this->branded = $opts["branded"];
$this->subscribed = $opts["isSubscribed"];
$this->type = $opts["type"];
$this->attributes["channel-external-id"] = $opts["channelExternalId"];
$this->attributes["params"] = $opts["params"];
$this->tooltip = $opts["tooltip"];
if ($this->subscribed) {
$this->style .= "STYLE_SUBSCRIBED";
$this->class[] = "hover-enabled";
$this->attributes += ["is-subscribed" => "True"];
} else {
$this->style .= "STYLE_SUBSCRIBE";
}
if ($this->branded)
{
$this->style .= "_BRANDED";
$this->attributes["style-type"] = "branded";
}
else
{
$this->style .= "_UNBRANDED";
$this->attributes["style-type"] = "unbranded";
}
if (!is_null($opts["href"]))
{
$this->href = $opts["href"];
}
$this->text = (object) ["runs" => [
(object) [
"text" => $opts["subscribeText"],
"class" => "subscribe-label"
],
(object) [
"text" => $opts["subscribedText"],
"class" => "subscribed-label"
],
(object) [
"text" => $opts["unsubscribeText"],
"class" => "unsubscribe-label"
]
]];
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common\Subscription;
use Rehike\Model\Common\MButton;
use Rehike\i18n;
class MSubscriptionPreferencesOverlay {
public string $title;
/** @var MSubscriptionPreference[] */
public array $options = [];
public MButton $saveButton;
public MButton $cancelButton;
public function __construct($data) {
$i18n = i18n::getNamespace("main/misc");
$this->title = $i18n->notificationPrefsTitle($data["title"]);
$this->saveButton = new MButton([
"style" => "STYLE_PRIMARY",
"size" => "SIZE_DEFAULT",
"text" => (object) [
"simpleText" => $i18n->btnSave
],
"class" => [
"overlay-confirmation-preferences-update-frequency",
"yt-uix-overlay-close"
]
]);
$this->cancelButton = new MButton([
"style" => "STYLE_DEFAULT",
"size" => "SIZE_DEFAULT",
"text" => (object) [
"simpleText" => $i18n->btnCancel
],
"class" => ["yt-uix-overlay-close"]
]);
foreach ($data["options"] as $option)
if ($option->menuServiceItemRenderer->icon->iconType != "PERSON_MINUS")
// ^ Filter out "Unsubscribe" item
{
$this->options[] = MSubscriptionPreference::fromData($option);
}
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common\Subscription;
use Rehike\i18n;
use Rehike\TemplateFunctions;
class MSubscriptionActions
{
public $showUnsubConfirmDialog = true;
public $showSubscriptionPreferences = true;
public $subscriberCountText = "";
public $shortSubscriberCountText = "";
/** @var MSubscriptionButton */
public $subscriptionButton;
/** @var MSubscriberCount */
public $subscriberCountRenderer;
public $unsubConfirmDialog;
public $subscriptionPreferencesButton;
public function __construct($opts)
{
$i18n = i18n::getNamespace("main/misc");
// Default options
$opts += [
"longText" => "",
"shortText" => "",
"showCount" => true,
"isDisabled" => false,
"isSubscribed" => false,
"type" => "FREE",
"branded" => "true",
"channelExternalId" => "",
"params" => "",
"subscribeText" => $i18n->get("subscribeText"),
"subscribedText" => $i18n->get("subscribedText"),
"unsubscribeText" => $i18n->get("unsubscribeText"),
"tooltip" => null,
"unsubConfirmDialog" => null,
"notificationStateId" => 3,
"href" => null
];
$this->unsubConfirmDialog = $opts["unsubConfirmDialog"];
if ($a = @$this->unsubConfirmDialog->confirmButton->buttonRenderer) {
$a->class = [
"overlay-confirmation-unsubscribe-button",
"yt-uix-overlay-close"
];
}
if ($a = @$this->unsubConfirmDialog->cancelButton->buttonRenderer) {
$a->class = ["yt-uix-overlay-close"];
$a->style = "STYLE_DEFAULT";
}
if ($opts["showCount"])
{
$this->subscriberCountText = $opts["longText"];
$this->shortSubscriberCountText = $opts["shortText"];
}
$this->subscriptionButton = new MSubscriptionButton([
"isDisabled" => $opts["isDisabled"],
"isSubscribed" => $opts["isSubscribed"],
"type" => $opts["type"],
"branded" => $opts["branded"],
"channelExternalId" => $opts["channelExternalId"],
"params" => $opts["params"],
"tooltip" => $opts["tooltip"],
"href" => $opts["href"],
"subscribeText" => $opts["subscribeText"],
"subscribedText" => $opts["subscribedText"],
"unsubscribeText" => $opts["unsubscribeText"]
]);
$this->subscriptionPreferencesButton = new MSubscriptionPreferencesButton($opts["channelExternalId"], $opts["notificationStateId"]);
if ($opts["longText"])
{
$this->subscriberCountRenderer = new MSubscriberCount(
$opts["longText"], $opts["branded"], "horizontal"
);
}
}
public static function fromData($data, $count = "", $branded = true)
{
return new self([
"branded" => $branded,
"longText" => $count,
"shortText" => $count,
"isSubscribed" => $data->subscribed ?? false,
"channelExternalId" => $data->channelId ?? "",
"params" => $data->onSubscribeEndpoints[0] ->subscribeEndpoint->params ?? null,
"subscribeText" => TemplateFunctions::getText($data->unsubscribedButtonText ?? null),
"subscribedText" => TemplateFunctions::getText($data->subscribedButtonText ?? null),
"unsubscribeText" => TemplateFunctions::getText($data->unsubscribeButtonText ?? null),
"unsubConfirmDialog" => $data->onUnsubscribeEndpoints[0] ->signalServiceEndpoint->actions[0] ->openPopupAction->popup->confirmDialogRenderer ?? null,
"notificationStateId" => $data->notificationPreferenceButton->subscriptionNotificationToggleButtonRenderer->currentStateId ?? 3
]);
}
public static function buildMock($count = "", $branded = true)
{
$i18n = i18n::getNamespace("main/misc");
return new self([
"isDisabled" => true,
"isSubscribed" => false,
"longText" => $count,
"shortText" => $count,
"branded" => $branded,
"tooltip" => $i18n->selfSubscribeTooltip
]);
}
public static function signedOutStub($count = "", $branded = true) {
return new self([
"longText" => $count,
"shortText" => $count,
"branded" => $branded,
"href" => "https://accounts.google.com/ServiceLogin?service=youtube&uilel=3&hl=en&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fapp%3Ddesktop%26action_handle_signin%3Dtrue%26hl%3Den%26next%3D%252F%26feature%3Dsign_in_button&passive=true"
]);
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common\Subscription;
use Rehike\Model\Common\MButton;
use Rehike\i18n;
class MSubscriptionPreferencesButton extends MButton {
public $class = [
"yt-uix-subscription-preferences-button"
];
public function __construct($ucid, $stateId) {
$i18n = i18n::getNamespace("main/misc");
$this->attributes["channel-external-id"] = $ucid;
$this->accessibility = (object) [
"accessibilityData" => (object) [
"live" => "polite",
"busy" => "false",
"role" => "button",
"label" => $i18n->notificationPrefsLabel
]
];
$this->icon = (object) [
"iconType" => "SUBSCRIPTION_PREFERENCES"
];
switch ($stateId) {
case 0:
$this->class[] = "yt-uix-subscription-notifications-none";
break;
case 2:
$this->class[] = "yt-uix-subscription-notifications-all";
break;
}
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common\Subscription;
/**
* Implements a model for the subscription count element
* that shows next to the actions.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
class MSubscriberCount
{
public $simpleText;
public $branded = true;
public $direction = "horizontal";
public function __construct($text, $branded = true, $direction = "horizontal")
{
$this->simpleText = $text;
$this->branded = $branded;
$this->direction = $direction;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common\Subscription;
use Rehike\TemplateFunctions;
class MSubscriptionPreference
{
public string $label;
public bool $checked;
public string $params;
public string $class;
public function __construct(array $data)
{
$this->label = $data["label"] ?? "";
$this->checked = $data["checked"] ?? false;
$this->params = $data["params"] ?? false;
$this->class = $data["class"] ?? false;
}
public static function fromData(object $data): self
{
$item = $data->menuServiceItemRenderer ?? null;
return new self([
"label" => TemplateFunctions::getText($item->text) ?? "",
"checked" => $item->isSelected ?? false,
"params" => $item->serviceEndpoint->modifyChannelNotificationPreferenceEndpoint->params ?? "",
"class" => match ($item->icon->iconType)
{
"NOTIFICATIONS_ACTIVE" => "receive-all-updates",
"NOTIFICATIONS_NONE" => "receive-highlight-updates",
"NOTIFICATIONS_OFF" => "receive-no-updates",
default => ""
}
]);
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common\Thumb;
class MThumbSimple {
public $type = "simple";
/** @var string */
public $image;
/** @var double */
public $width;
/** @var double */
public $height;
/** @var string */
public $alt;
/** @var bool */
public $delayload = false;
public function __construct($data) {
$this->image = $data["image"] ?? "";
$this->width = $data["width"] ?? 0;
$this->height = $data["height"] ?? 0;
$this->alt = $data["alt"] ?? "";
$this->delayload = $data["delayload"] ?? false;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common\Thumb;
class MThumbSquare extends MThumbSimple {
public $type = "square";
public function __construct($data) {
$this->image = $data["image"] ?? "";
$this->width = $data["size"] ?? 0;
$this->height = $data["size"] ?? 0;
$this->alt = $data["alt"] ?? "";
$this->delayload = $data["delayload"] ?? false;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common\Menu;
class MMenu {
/** @var MMenuItem[] */
public $items = [];
/** @var string[] */
public $containerClass = [];
/** @var string */
public $menuId;
/** @var string[] */
public $menuClass = [];
public function __construct($data) {
foreach ($data["items"] as $item) {
$this->items[] = new MMenuItem($item);
}
$this->containerClass = $data["containerClass"];
$this->menuId = $data["menuId"];
$this->menuClass = $data["menuClass"];
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Common\Menu;
#[\AllowDynamicProperties]
class MMenuItem {
/** @var string */
public $label;
/** @var string[] */
public $class = [];
/** @var bool */
public $hasIcon = false;
public function __construct($data) {
foreach ($data as $key => $val) {
$this->{$key} = $val;
}
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\ChannelSwitcher;
use Rehike\TemplateFunctions as TF;
use Rehike\Util\ParsingUtils;
use Rehike\i18n;
// TODO: video counts, which can be done like so:
/*
Request::queueInnertubeRequest("id", ""creator/get_creator_channels", (object) [
"channel_array" => channelIds
])
*/
class ChannelSwitcherModel
{
public static function bake(?array $channels, ?object $switcher, ?string $next)
{
$response = (object) [];
$response->channels = [];
$i18n = i18n::newNamespace("channel_switcher");
$i18n->registerFromFolder("i18n/channel_switcher");
$response->headerTextPrefix = $i18n->pageHeaderPrefix;
$response->learnMoreLinkText = $i18n->learnMoreLink;
foreach ($channels as $channel)
{
if (isset($channel->accountItemRenderer))
{
$response->channels[] = (object) [
"accountItemRenderer" => new MChannelItem($channel->accountItemRenderer, $next)
];
}
elseif (isset($channel->buttonRenderer))
{
$response->channels[] = (object) [
"createChannelItemRenderer" => new MCreateChannelItem($channel->buttonRenderer)
];
}
}
$response->email = ParsingUtils::getText(
@$switcher->data->actions[0]->getMultiPageMenuAction
->menu->multiPageMenuRenderer->sections[0]
->accountSectionListRenderer->header->googleAccountHeaderRenderer->email
);
return $response;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\ChannelSwitcher;
use Rehike\Util\ParsingUtils;
class MCreateChannelItem
{
public string $text;
public function __construct(object $data)
{
$this->text = ParsingUtils::getText($data->text);
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\ChannelSwitcher;
use Rehike\i18n;
use Rehike\Util\ParsingUtils;
use Rehike\TemplateFunctions as TF;
class MChannelItem
{
public bool $selected = false;
public string $ucid;
public string $url;
public string $avatar;
public string $title;
public string $subscriberCountText;
public function __construct(object $data, ?string $next)
{
$i18n = i18n::getNamespace("channel_switcher");
$this->selected = $data->isSelected;
$this->avatar = ParsingUtils::getThumb($data->accountPhoto, 56);
$this->title = ParsingUtils::getText(@$data->accountName);
$this->subscriberCountText = $data->hasChannel
? ParsingUtils::getText(@$data->accountByline)
: $i18n->ownerAccountNoChannel;
$tokenRoot = $data->serviceEndpoint->selectActiveIdentityEndpoint->supportedTokens;
foreach($tokenRoot as $token)
{
if (isset($token->offlineCacheKeyToken))
{
$this->ucid = "UC" . $token->offlineCacheKeyToken->clientCacheKey;
}
elseif (isset($token->accountSigninToken))
{
$this->url = $token->accountSigninToken->signinUrl;
}
}
// Apply next URL param to switch links
if (!is_null($next))
{
$this->url = preg_replace("/(?<=\?|&)next=(.*?)(?=&|$)/", "next=$next", $this->url);
}
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Model\Browse;
use Rehike\i18n;
use Rehike\TemplateFunctions as TF;
use Rehike\Util\ExtractUtils;
use Rehike\Model\Channels\Channels4\BrandedPageV2\MSubnav;
use Rehike\Signin\API as SignIn;
use Rehike\Model\Common\Subscription\MSubscriptionActions;
class InnertubeBrowseConverter
{
public static function generalLockupConverter($items, $context = [])
{
foreach ($items as &$item) foreach ($item as $name => &$content)
{
switch ($name)
{
case "channelRenderer":
case "gridChannelRenderer":
$content = self::channelRenderer($content, $context);
break;
case "videoRenderer":
case "gridVideoRenderer":
case "compactVideoRenderer":
$content = self::videoRenderer($content, $context);
break;
case "richItemRenderer":
$content = self::richItemRenderer($content, $context);
break;
case "reelItemRenderer":
case "gridReelItemRenderer":
$list = $context["listView"] ?? false;
$item->{$list ? "videoRenderer" : "gridVideoRenderer"}
= self::reelItemRenderer($content, $context);
unset($item->reelItemRenderer);
break;
}
}
return $items;
}
/**
* Process a grid renderer.
*
* This is, for the most part, supported natively. This
* method exists in order to streamline replacement of children
* of grid renderers that may actually need to be modified.title
*/
public static function gridRenderer($data, $context = [])
{
$data->items = self::generalLockupConverter($data->items, $context);
return $data;
}
/**
* Process a shelf renderer.
*
* This is also, for the most part, supported natively.
* Ditto above.
*/
public static function shelfRenderer($data, $context = [])
{
foreach ($data->content as $name => &$value)
{
switch ($name)
{
case "verticalListRenderer":
case "horizontalListRenderer":
case "expandedShelfContentsRenderer":
$value->items = self::generalLockupConverter($value->items, $context);
break;
}
}
return $data;
}
/**
* Process an item section renderer.
*
* Again, mostly natively supported, but we want to
* easily modify any lockups that need it.
*/
public static function itemSectionRenderer($data, $context = [])
{
foreach ($data->contents as &$content) foreach ($content as $name => &$value)
{
switch ($name)
{
case "shelfRenderer":
$value = self::shelfRenderer($value, $context);
break;
case "channelRenderer":
case "gridChannelRenderer":
$value = self::channelRenderer($value, $context);
break;
case "videoRenderer":
case "gridVideoRenderer":
$value = self::videoRenderer($value, $context);
break;
case "channelFeaturedContentRenderer":
$value->items = self::generalLockupConverter($value->items, $context);
break;
}
}
return $data;
}
/**
* Process a section list renderer.
*
* Again, mostly natively supported, but we want to
* easily modify any lockups that need it.
*/
public static function sectionListRenderer($data, $context = [])
{
foreach ($data->contents as &$content) foreach ($content as $name => &$value)
{
switch ($name)
{
case "itemSectionRenderer":
$value = self::itemSectionRenderer($value, $context);
break;
}
}
return $data;
}
public static function channelRenderer($data, $context = [])
{
if (i18n::namespaceExists("browse/converter")) {
$i18n = i18n::getNamespace("browse/converter");
} else {
$i18n = i18n::newNamespace("browse/converter");
$i18n->registerFromFolder("i18n/browse");
}
if (@$context["channelRendererNoSubscribeCount"])
$subscriberCount = "";
else if (isset($data->subscriberCountText))
$subscriberCount = ExtractUtils::isolateSubCnt(TF::getText($data->subscriberCountText));
$subscriberCount = $subscriberCount ?? "";
$subscribeButtonBranded = true;
/**
* You know, I hate this. At first it was fun.
* I was able to easily make things with a
* competent API. however, they stopped being
* fucking competent in 2022. For the handles
* update they decided it would be a BRIGHT
* FUCKING IDEA to move the subscription count
* to the video count text, and put the handle
* in the subscription count text. How FUCKING
* HARD IS IT TO ADD ANOTHER FIELD?!?!?!?!?!!?
* HOW FUCKING HARD?!?!?!!?!?!?!?!?!!?! WHAT
* THE ACTUAL FUCK?!?!!?!?!? FUCKING DIE IN A
* DITCH, HOLY FUCKING SHIT.
* - love, aubrey <3
*/
if (substr($subscriberCount, 0, 1) == "@") {
$subscriberCount = ExtractUtils::isolateSubCnt(TF::getText($data->videoCountText));
unset($data->videoCountText);
}
if (@$context["channelRendererUnbrandedSubscribeButton"])
$subscribeButtonBranded = false;
if (@$context["channelRendererChannelBadge"]) {
if (!isset($data->badges)) {
$data->badges = [];
}
$data->badges[] = (object) [
"metadataBadgeRenderer" => (object) [
"label" => $i18n->channelBadge,
"style" => "BADGE_STYLE_TYPE_SIMPLE"
]
];
}
if (isset($data->subscribeButton->subscribeButtonRenderer))
{
$data->subscribeButton = MSubscriptionActions::fromData(
$data->subscribeButton->subscribeButtonRenderer,
$subscriberCount,
$subscribeButtonBranded
);
}
elseif (SignIn::isSignedIn())
{
$data->subscribeButton = MSubscriptionActions::buildMock(
$subscriberCount,
$subscribeButtonBranded
);
}
else
{
$data->subscribeButton = MSubscriptionActions::signedOutStub(
$subscriberCount,
$subscribeButtonBranded
);
}
if (@$context["channelRendererNoMeta"])
{
unset($data->subscriberCountText);
}
return $data;
}
public static function videoRenderer($data, $context = [])
{
$regex = i18n::getNamespace("main/regex");
if (i18n::namespaceExists("browse/converter"))
{
$i18n = i18n::getNamespace("browse/converter");
}
else
{
$i18n = i18n::newNamespace("browse/converter");
$i18n->registerFromFolder("i18n/browse");
}
if (isset($data->badges))
foreach ($data->badges as $badge) foreach ($badge as &$content)
{
if ($content->style == "BADGE_STYLE_TYPE_LIVE_NOW"
&& $content->label == $i18n->liveBadgeOriginal)
{
$content->label = $i18n->liveBadge;
}
}
if (isset($data->thumbnailOverlays))
foreach ($data->thumbnailOverlays as $index => &$overlay) foreach ($overlay as $name => &$content)
{
switch ($name)
{
case "thumbnailOverlayTimeStatusRenderer":
switch ($content->style)
{
case "LIVE":
if (!isset($data->badges))
$data->badges = [];
$data->badges[] = (object) [
"metadataBadgeRenderer" => (object) [
"label" => $i18n->liveBadge,
"style" => "BADGE_STYLE_TYPE_LIVE_NOW"
]
];
array_splice($data->thumbnailOverlays, $index);
break;
case "SHORTS":
$content->style = "DEFAULT";
$atitle = $data->title->accessibility->accessibilityData->label;
preg_match($regex->videoTimeIsolator, $atitle, $matches);
$text = null;
if (!isset($matches[0]))
{
$text = "1:00";
}
else
{
$time = (int) preg_replace($regex->secondsIsolator, "", $matches[0]);
if ($time < 10)
{
$text = "0:0$time";
}
else
{
$text = "0:$time";
}
}
$content->text = (object) [
"simpleText" => $text
];
break;
}
break;
}
}
return $data;
}
/**
* Convert a rich grid renderer to regular grid renderer
*/
public static function richGridRenderer($data, $context = [])
{
$items = [];
foreach ($data->contents as $item)
{
if (@$item->richItemRenderer)
{
$items[] = self::richItemRenderer($item->richItemRenderer);
}
else if (@$item->continuationItemRenderer)
{
$items[] = $item;
}
}
return (object)[
"items" => $items
];
}
/**
* Convert a rich item renderer to its canonical type.
*
* @return object
*/
public static function richItemRenderer($data, $context = [])
{
if (!@$context["listView"])
{
foreach ($data->content as $name => $value)
{
return (object) [
"grid" . ucfirst($name) => $value
];
}
}
return $data->content;
}
public static function reelItemRenderer(object $data, array $context = []): object
{
$data->title = $data->headline;
unset($data->headline);
return $data;
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
use SpfPhp\SpfPhp;
/**
* A custom redirect handler that takes SPF into account.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
return function($url) {
if (SpfPhp::isSpfRequested())
{
$spfRegexp = '/(\?|&)spf=[A-Za-z0-9]*/';
http_response_code(200);
echo json_encode((object)[
"redirect" => preg_replace($spfRegexp, "", $url)
]);
die();
}
else
{
http_response_code(302);
header("Location: $url");
die();
}
}; | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
require "modules/Rehike/ErrorHandler/ErrorHandler.php"; | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
$yts = "//s.ytimg.com/yts/";
$img = $yts . "img/";
$css = $yts . "cssbin/";
$js = $yts . "jsbin/";
$mod = $js . "www-en_US-vfl2g6bso/";
return (object) [
"pixelGif" => "{$img}pixel-vfl3z5WfW.gif",
"css" => (object) [
"www-core" => "{$css}www-core-vflZ7bM6S.css",
"www-pageframe" => "{$css}www-pageframe-vflhkpWhK.css",
"www-highcontrastmode" => "{$css}www-highcontrastmode-vflCxtOoT.css",
"www-guide" => "{$css}www-guide-vflNDDMf7.css",
"www-home-c4" => "{$css}www-home-c4-vflopQeuE.css",
"www-attribution" => "{$css}www-attribution-vflhQnyPy.css",
"www-results" => "{$css}www-results-vfl67U2zJ.css",
"www-account-settings" => "{$css}www-account-settings-vfl9mNWIu.css",
"www-creatorpage" => "{$css}www-creatorpage-vflfgomxn.css",
"www-error" => "{$css}www-error-vflvD9R0Z.css",
"www-live-chat" => "{$css}www-live-chat-vflGrXn94.css",
"www-livestreaming-chatbadges" => "{$css}www-livestreaming-chatbadges-vfl5EBaFs.css",
"www-livestreaming_chat_emoji" => "{$css}www-livestreaming_chat_emoji-vfl49K1WZ.css",
"www-channels4edit" => "{$css}www-channels4edit-vflUEQcbz.css",
"www-watch-inlineedit" => "{$css}www-watch-inlineedit-vflpewV3h.css",
"www-watch-transcript" => "{$css}www-watch-transcript-vflp9_n_i.css",
"www-channelswitcher" => "{$css}www-channelswitcher-webp-vflMtLwIV.css"
],
"css2x" => (object) [
"www-core" => "{$css}www-core-2x-vflNAXaGB.css",
"www-pageframe" => "{$css}www-pageframe-2x-vfl7zB5iD.css",
"www-guide" => "{$css}www-guide-2x-vflnLcFfr.css",
"www-home-c4" => "{$css}www-home-c4-2x-vflBmvDSR.css",
"www-results" => "{$css}www-results-2x-vflilAG3t.css",
"www-error" => "{$css}www-error-2x-vflvD9R0Z.css",
"www-watch-transcript" => "{$css}www-watch-transcript-2x-vflp9_n_i.css"
],
"jsModulesPath" => $mod,
"js" => (object) [
"scheduler/scheduler" => "{$js}scheduler-vflyNP9EQ/scheduler.js",
"spf/spf" => "{$js}spf-vflRfjT3b/spf.js",
"www-core/www-core" => "{$js}www-core-vflWuPqdk/www-core.js",
"www-searchbox/www-searchbox" => "{$js}www-searchbox-vflV_B8yT/www-searchbox.js",
"www-notfound/www-notfound" => "{$js}www-notfound-vflsu8ylX/www-notfound.js",
"www/base" => "{$mod}base.js",
"www/common" => "{$mod}common.js",
"www/angular_base" => "{$mod}angular_base.js",
"www/channels_accountupload" => "{$mod}channels_accountupload.js",
"www/channels" => "{$mod}channels.js",
"www/dashboard" => "{$mod}dashboard.js",
"www/downloadreports" => "{$mod}downloadreports.js",
"www/experiments" => "{$mod}experiments.js",
"www/feed" => "{$mod}feed.js",
"www/instant" => "{$mod}instant.js",
"www/legomap" => "{$mod}legomap.js",
"www/promo_join_network" => "{$mod}promo_join_network.js",
"www/results_harlemshake" => "{$mod}results_harlemshake.js",
"www/results" => "{$mod}results.js",
"www/results_starwars" => "{$mod}results_starwars.js",
"www/subscriptionmanager" => "{$mod}subscriptionmanager.js",
"www/unlimited" => "{$mod}unlimited.js",
"www/watch" => "{$mod}watch.js",
"www/ypc_bootstrap" => "{$mod}ypc_bootstrap.js",
"www/ypc_core" => "{$mod}ypc_core.js",
"www/channels_edit" => "{$mod}channels_edit.js",
"www/live_dashboard" => "{$mod}live_dashboard.js",
"www/videomanager" => "{$mod}videomanager.js",
"www/watch_autoplayrenderer" => "{$mod}watch_autoplayrenderer.js",
"www/watch_edit" => "{$mod}watch_edit.js",
"www/watch_editor" => "{$mod}watch_editor.js",
"www/watch_live" => "{$mod}watch_live.js",
"www/watch_promos" => "{$mod}watch_promos.js",
"www/watch_speedyg" => "{$mod}watch_speedyg.js",
"www/watch_transcript" => "{$mod}watch_transcript.js",
"www/watch_videoshelf" => "{$mod}watch_videoshelf.js",
"www/ct_advancedsearch" => "{$mod}www/ct_advancedsearch.js",
"www/my_videos" => "{$mod}my_videos.js"
],
"img" => (object) [
"channels/c4/default_banner" => "{$img}channels/c4/default_banner-vfl7DRgTn.png",
"channels/c4/default_banner_hq" => "{$img}channels/c4/default_banner_hq-vfl4dpY8T.png",
"meh7" => "{$img}meh7-vflGevej7.png"
]
];
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Constants;
/*
* DEVELOPER NOTICE:
*
* Be careful modifying this file. Especially in the case of
* changing or removing an option.
*
* Make sure to check if these changes will not break anything.
*
* Thank you.
*/
/**
* Enables GitHub integration with some Rehike features.
*
* @var bool
*/
const GH_ENABLED = true;
/**
* Specifies the GitHub repository to link to.
*
* @var string
*/
const GH_REPO = "Rehike/Rehike";
/**
* The current version of Rehike.
*
* @var string
*/
const VERSION = "0.7";
const VERSION_MAJOR_INT = 0;
const VERSION_MINOR_INT = 7;
/**
* The location of views (templates) relative to the root.
*
* @var string
*/
const VIEWS_DIR = "template/hitchhiker"; | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace RehikeBase;
use Exception;
// Functions cannot be autoloaded, so load them manually.
require "includes/functions/async.php";
require "includes/functions/safe_class_alias.php";
/**
* Implements the Rehike autoloader.
*
* @version 2.0
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
class Autoloader
{
// shhhh :3
public const autoload = self::class . "::autoload";
protected static array $classAliases = [];
/**
* The main autoloader function.
*/
public static function autoload(string $class): void
{
// PHP classes are separated by "\", which works just fine on Windows,
// but will fail on other operating systems. This is required in order
// to load on *nix.
$PATH = str_replace("\\", "/", $class);
if (
self::fileExists($f = "modules/$PATH.php") ||
self::fileExists($f = "modules/generated/$PATH.php") ||
self::mapPrefix($PATH, "Rehike/Model/", "models/", $f) ||
self::mapPrefix($PATH, "Rehike/Controller/", "controllers/", $f)
)
{
self::tryImportClass($f, $class);
}
// Implements the fake magic method __initStatic for automatically
// initialising static classes.
if (\method_exists($class, "__initStatic"))
{
$class::__initStatic();
}
}
static function tryImportClass(string $path, string $class): void
{
@$status = include $path;
if (true == $status)
{
if (
\class_exists($class, false) ||
\interface_exists($class, false) ||
\trait_exists($class, false) ||
(PHP_VERSION_ID > 81000 && \enum_exists($class, false))
)
{
/*
* PHP class names are case-insensitive, which doesn't bother the
* Windows filesystem (because of course it doesn't), however,
* proper operating systems have case-sensitive file names.
*
* This means a simple casing typo in an import can go completely
* unnoticed by our Windows-using developers, yet break support
* for Linux and macOS, where file_exists() would return false.
*
* This is a check for said Windows developers. This compares the
* requested class name ($class) with the actual class name.
*/
if ( ($a = new \ReflectionClass($class))->name !== $class )
{
// This can also be true for class aliases, so it's important
// to be careful here. Class aliases are always defined as
// lowercase to the PHP interpreter, so the check is not
// performed for class_alias results. Use Rehike\safeClassAlias()
// instead.
if (strtolower($a->name) === strtolower($class))
{
// This is 100% a casing issue, report it to the user.
throw new Exception(
"Class case error loading class $class (unknown case do not trust the error!)"
);
}
else if (
self::hasClassAlias($class) &&
self::getClassAlias($class) !== $class
)
{
// This is also a known casing issue.
throw new Exception(
"Class case error loading class $class (unknown case do not trust the error!)"
);
}
}
}
else
{
throw new Exception("Loaded file $path but no class by that name exists");
}
}
else
{
throw new Exception("Failed to import class $path");
}
}
/**
* Registers a known class alias that is safely cased.
*/
public static function registerClassAlias(string $alias): void
{
self::$classAliases[strtolower($alias)] = $alias;
}
static function hasClassAlias(string $alias): bool
{
return isset(self::$classAliases[strtolower($alias)]);
}
static function getClassAlias(string $alias): string
{
return self::$classAliases[strtolower($alias)];
}
/**
* Checks if a file exists from the root of the server.
*
* This practically emulates using the include path, which file_exists
* otherwise does not support.
*
* Additionally, the check is performed case-sensitively, so a non-existent
* file can be easily detected.
*/
static function fileExists(string $filename): bool
{
$path = $_SERVER["DOCUMENT_ROOT"] . "/" . $filename;
return
\file_exists($path) &&
\basename(\realpath($path)) === \basename($path)
;
}
/**
* Checks if a string starts with a substring.
*/
static function mapPrefix(
string $filename,
string $prefix,
string $basedir,
string &$out
): bool
{
$len = \strlen($prefix);
$out = $basedir . substr($filename, $len) . ".php";
return $prefix == \substr($filename, 0, $len);
}
}
spl_autoload_register(Autoloader::autoload);
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\ErrorHandler\FatalErrorTemplate;
$minimumPhpVersion = "8.0";
?>
<!DOCTYPE html>
<html>
<head>
<title>Rehike startup error</title>
<?php include "fatal.css.php" ?>
</head>
<body>
<div id="rehike-fatal-error">
<div class="header">
<svg xmlns="http://www.w3.org/2000/svg" height="48px" viewBox="0 0 24 24" width="48px" fill="#cc181e">
<path d="M0 0h24v24H0z" fill="none" />
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z" />
</svg>
<h1>Your version of PHP is too old!</h1>
</div>
<p>
Rehike requires at least <b>PHP <?php echo $minimumPhpVersion ?></b>. You are using
<b>PHP <?php echo PHP_VERSION ?></b>.
</p>
<p>
Please update PHP and try again.
</p>
</div>
</body>
</html> | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php ?>
<style>
html, body
{
min-height: 100vh;
}
body
{
margin: 0;
font-family: Arial, Helvetica, sans-serif;
font-size: 13px;
background: #f1f1f1;
display: flex;
justify-content: center;
align-items: center;
}
#rehike-fatal-error
{
width: 800px;
padding: 15px;
margin: 0 auto;
background: #fff;
box-shadow: 0 1px 2px rgba(0,0,0,.1);
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.header > *
{
vertical-align: middle;
}
.header h1
{
display: inline;
}
<?php
// Error log text styling:
?>
ul.fatal-error-info
{
list-style: none;
}
.fatal-error-info .section-title
{
font-weight: bold;
}
.fatal-error-info li
{
margin-bottom: 3px;
}
.no-message
{
color: #666;
font-style: italic;
}
.exception-log
{
word-wrap: break-word;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
}
.exception_class
{
font-weight: bold;
}
.at_text
{
color: #666;
}
.class_name, .double_colon_operator
{
color: #990080;
}
.method_name, .function_name
{
font-style: italic;
font-weight: bold;
color: #99112c;
}
.file_line_parentheses, .file_line
{
color: #666;
}
.args_type_object
{
color: #8a2be2;
}
.args_type_string
{
color: #008000;
}
.args_type_number
{
color: #1f47e3;
}
.args_type_resource, .args_type_null, .args_type_unknown, .args_type_array
{
color: #333;
}
</style> | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\ErrorHandler\FatalErrorTemplate;
use Rehike\Logging\Common\FormattedString;
function simpleFormattedStringToHtml(FormattedString $fs): string
{
$out = "";
foreach ($fs->getRuns() as $run)
{
if (isset($run["tag"]))
{
$out .=
"<span class=\"" . htmlspecialchars($run["tag"]) . "\">" .
htmlspecialchars($run["text"]) .
"</span>";
}
else
{
$out .= htmlspecialchars($run["text"]);
}
}
return $out;
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\ErrorHandler\FatalErrorTemplate;
use Rehike\ErrorHandler\ErrorHandler;
use Rehike\ErrorHandler\ErrorPage\UncaughtExceptionPage;
use Rehike\ErrorHandler\ErrorPage\FatalErrorPage;
use const Rehike\Constants\GH_ENABLED;
use const Rehike\Constants\GH_REPO;
include_once "includes/fatal_templates/fatal_template_functions.php";
$page = ErrorHandler::getErrorPageModel();
?>
<!DOCTYPE html>
<!-- thanks aubrey <33 -->
<html>
<head>
<title>Rehike fatal error</title>
<?php include "fatal.css.php" ?>
</head>
<body>
<div id="rehike-fatal-error">
<div class="header">
<svg xmlns="http://www.w3.org/2000/svg" height="48px" viewBox="0 0 24 24" width="48px" fill="#cc181e">
<path d="M0 0h24v24H0z" fill="none" />
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z" />
</svg>
<h1><?= $page->getTitle() ?></h1>
</div>
<p>
A fatal error has occurred and Rehike cannot continue. Sorry for the inconvenience.
<?php if (true == GH_ENABLED): ?>
<div class="github-link">
<a href="//github.com/<?= GH_REPO ?>/issues/new">
Please submit an issue to the GitHub repository, including the crash log.
</a>
</div>
<?php endif ?>
<?php if ($page instanceof UncaughtExceptionPage): ?>
<pre class="exception-log"><?=
simpleFormattedStringToHtml($page->getExceptionLog())
?></pre>
<?php elseif ($page instanceof FatalErrorPage): ?>
<ul class="fatal-error-info">
<li class="fatal-error-type">
<span class="section-title">
Error type:
</span>
<?= htmlspecialchars($page->getType()) ?>
</li>
<li class="fatal-error-file">
<span class="section-title">
File:
</span>
<?= htmlspecialchars($page->getFile()) ?>
</li>
<li class="fatal-error-message">
<span class="section-title">
Message:
</span>
<?php if ($page->hasMessage()): ?>
<?= htmlspecialchars($page->getMessage()) ?>
<?php else: ?>
<span class="no-message">
No message provided.
</span>
<?php endif ?>
</li>
</ul>
<?php endif ?>
</p>
</div>
</body>
</html> | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike\Async;
const ASYNC_FUNCTION_FILE = __FILE__;
/**
* Declares an async function.
*
* This is an abstraction for Promises using PHP's native generator
* functionality. It functions very similarly to async functions in
* C# or ECMAScript 7. The main difference is it relies on an anonymous
* function still, and uses the `yield` keyword rather than `await`.
*
* For API compatiblity with standard Promises, all async functions
* return a Promise which will resolve or reject with the internal
* Generator it uses.
*
* Usage example:
*
* function requestExample(string $url): Promise//<Response>
* {
* return async(function() use (&$myPromises) {
* echo "Making network request...";
*
* $result = yield Network::request($url);
*
* if (200 == $result->status)
* {
* return $result;
* }
* else
* {
* throw new NetworkFailedExeception($result);
* }
* });
* }
*
* This is like the following C# code:
*
* async Task<Response> requestExample(string url)
* {
* System.Console.WriteLine("Making network request...");
*
* Response result = await Network.request(url);
*
* if (200 == result.status)
* {
* return result;
* }
* else
* {
* throw new NetworkFailedException(result);
* }
* }
*
* or the following TypeScript code:
*
* async function requestExample(url: string): Promise<Response>
* {
* console.log("Making network request...");
*
* let result = await Network.request(url);
*
* if (200 == request.status)
* {
* return result;
* }
* else
* {
* throw new NetworkFailedException(result);
* }
* }
*
* Notice that both languages also return their respective wrapper
* type for all asynchronous functions. This is for API-compatibility
* with other approaches. It is also important to keep in consideration!
*
* PHP developers who are unfamiliar with asynchronous design may think
* that an async function returns the type it returns, but it simply
* provides syntax to work with Promises in a synchronous manner.
* Remember that *ANY* function which needs to use the result of an
* asynchronous function must also do so asynchronously, either by using
* Promise::then() or implementing its body in an async stream.
*
* @template T
* @param callable<T> $cb
* @return Promise<T>
*/
function async/*<T>*/(callable/*<T>*/ $cb): Promise/*<T>*/
{
return Concurrency::async($cb);
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace Rehike;
use function class_alias;
/**
* Implements a safe version of class_alias that retains casing.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
function safeClassAlias(string $class, string $alias, bool $autoload = true): void
{
\RehikeBase\Autoloader::registerClassAlias($alias);
class_alias($class, $alias, $autoload);
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
use \Rehike\ControllerV2\Util\GlobToRegexp;
/**
* An fnmatch polyfill for certain PHP configurations, most
* notably old PHP on Windows.
*
* This is based on the GlobToRegexp behaviour of ControllerV2. With
* that said, I got lazy writing this. If you're moving CV2 at all,
* make sure to accomodate those changes here.
* Love, Taniko.
*
* @see https://www.php.net/manual/en/function.fnmatch.php#100207
*/
if (!function_exists("fnmatch"))
{
define("FNM_PATHNAME", GlobToRegexp::PATHNAME);
define("FNM_NOESCAPE", GlobToRegexp::NOESCAPE);
define("FNM_PERIOD", GlobToRegexp::PERIOD);
define("FNM_CASEFOLD", GlobToRegexp::CASEFOLD);
/**
* @param string $pattern
* @param string $filename
* @param int $flags
*/
function fnmatch($pattern, $filename, $flags = 0)
{
return GlobToRegexp::doMatch($pattern, $filename, $flags);
}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
// Just a fix for IDEs. PHP itself doesn't care about illegal class
// names used as attributes and will continue executing anyways.
// Still, this is safer.
if (!class_exists("AllowDynamicProperties")) // PHP 8.1 and prior
{
#[Attribute()]
final class AllowDynamicProperties {}
} | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/**
* Generate a template level RID.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*/
\Rehike\TemplateFunctions::register('generateRid', function() {
return rand(100000, 999999);
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register('getThumb', function($obj, $height = 0) {
if (isset($obj->thumbnail->thumbnails)) {
$thumbs = $obj->thumbnail->thumbnails;
} else if (isset($obj->thumbnails)) {
$thumbs = $obj->thumbnails;
}
if (!isset($thumbs)) return "//i.ytimg.com/";
if (isset($height) && $height != 0){
for ($i = 0; $i < count($thumbs); $i++) {
if ($thumbs[$i] ->height >= $height) {
$thumb = $thumbs[$i];
}
}
} else {
$thumb = $thumbs[array_key_last($thumbs)];
}
if (isset($thumb->width) && isset($thumb->height)) {
$ratio = $thumb->width / $thumb->height;
if ($ratio >= 1.7 && $ratio < 1.8) {
return $thumb->url;
} else {
return preg_replace("/\?sqp=.*/", "", $thumb->url);
}
} else {
return $thumb->url;
}
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
use Rehike\Util\Base64Url;
use Com\Youtube\Innertube\Navigation\NavigationEndpoint;
use Com\Youtube\Innertube\Navigation\NavigationEndpoint\BrowseEndpoint;
use Com\Youtube\Innertube\Navigation\NavigationEndpoint\UrlEndpoint;
/**
* Serialise a guide navigation endpoint in URL-base64 protobuf.
*
* This is very accurate to the official Hitchhiker implementation.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*
* @param object $endpoint
* @return string
*/
\Rehike\TemplateFunctions::register('serialiseEndpoint', function($endpoint) {
$pb = new NavigationEndpoint();
if (isset($endpoint->browseEndpoint))
{
$pb->setBrowseEndpoint(new BrowseEndpoint([
"browse_id" => $endpoint->browseEndpoint->browseId
]));
}
else if (isset($endpoint->urlEndpoint))
{
$pb->setUrlEndpoint(new UrlEndpoint([
"url" => $endpoint->urlEndpoint->url
]));
}
$data = $pb->serializeToString();
return Base64Url::encode($data);
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/**
* Helper function for finding the Watch Later button when building
* HTML templates.
*
* This iterates the overlays array and searches for the Watch
* Later button. If it's not present, this will return null.
*
* This is meant to be used as a helper function for Twig.
*
* @author Taniko Yamamoto <[email protected]>
*
* @param object $array of the thumbnail overlays
*
* @return ?object
*/
\Rehike\TemplateFunctions::register("getWLOverlay", function($array)
{
if (!isset($array->thumbnailOverlays )) return null;
foreach ($array->thumbnailOverlays as $index => $contents)
{
if (isset($contents->thumbnailOverlayToggleButtonRenderer) &&
"WATCH_LATER" == @$contents->thumbnailOverlayToggleButtonRenderer
->untoggledIcon->iconType
)
{
return $contents->thumbnailOverlayToggleButtonRenderer;
}
}
// Return null if the index doesn't exist.
return null;
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register('contentType', function($type) {
/*
* PATCH (kirasicecreamm): Prevent "headers already sent" warning in the
* case of multiple Twig calls, for example.
*/
@header('Content-Type: ' . $type);
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register('resolveBrowseIdUrl', function ($id) {
if (!isset($id)) {
return "";
}
$url = "";
$idType = substr($id, 0, 2);
$id = substr($id, 2, strlen($id));
switch ($idType) {
case 'UC':
$url = '/channel/UC' . $id;
break;
case 'FE':
default:
$url = '/feed/' . $id;
break;
}
return $url;
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/**
* Convert an object to an associative array.
*
* This is needed in order to iterate the keys of an object
* in Twig. Twig only supports iterating associative arrays, not
* objects.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*
* @param string $obj to cast
* @return array of the casted object
*/
\Rehike\TemplateFunctions::register('obj2arr', function($obj) {
return (array)$obj;
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register("getDescSnippet", function ($renderer) {
if (isset($renderer->descriptionSnippet)) return $renderer->descriptionSnippet;
if (isset($renderer->detailedMetadataSnippets[0] ->snippetText)) return $renderer->detailedMetadataSnippets[0] ->snippetText;
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register("cssPath", function($name, $pref, $constants) {
$css2x = false;
if (isset($pref->f4) && substr($pref->f4, 0, 1) == "4")
$css2x = true;
if ($css2x && isset($constants->css2x->{$name}))
return $constants->css2x->{$name};
return $constants->css->{$name} ?? "";
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register("imgPath", function($name, $constants) {
return $constants->img->{$name} ?? "";
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/**
* Get the type of a variable.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*
* @param string $data
* @return string
*/
\Rehike\TemplateFunctions::register('getType', function($data) {
return gettype($data);
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/**
* Resolve a guide endpoint (used for some attributes on guide items, like the IDs).
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*
* @param object $guideItem
* @return string
*/
\Rehike\TemplateFunctions::register('resolveGuideEndpoint', function($guideItem) {
// $guideItem = guideEntryRenderer
if (isset($guideItem->navigationEndpoint->browseEndpoint->browseId))
{
$id = $guideItem->navigationEndpoint->browseEndpoint->browseId;
// Remove FE substring if present
if ("FE" == substr($id, 0, 2))
{
$id = substr($id, 2);
}
return $id;
}
else
{
return "";
}
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register("resolveSize", function($const) {
return strtolower(str_replace(["SIZE_", "_"], ["", "-"], $const));
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/**
* Convert a CONSTANT_CASE string to a class-case string.
*
* This may be useful in a number of areas, but it's particularly
* useful for the guide.
*
* @author Taniko Yamamoto <[email protected]>
* @author The Rehike Maintainers
*
* @param string $const in CONSTANT_CASE
* @return string in class-case
*/
\Rehike\TemplateFunctions::register('const2class', function($const) {
return strtolower(str_replace("_", "-", $const));
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register("getByline", function($renderer) {
if (isset($renderer->longBylineText)) return $renderer->longBylineText;
if (isset($renderer->shortBylineText)) return $renderer->shortBylineText;
return null;
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register('getVideoTime', function($obj) {
if (isset($obj->lengthText)) {
return $obj->lengthText->simpleText;
} else if (isset($obj->thumbnailOverlays)) {
for ($i = 0; $i < count($obj->thumbnailOverlays); $i++) {
if (isset($obj->thumbnailOverlays[$i]->thumbnailOverlayTimeStatusRenderer)) {
$lengthText = $obj->thumbnailOverlays[$i]->thumbnailOverlayTimeStatusRenderer->text->simpleText;
}
}
if (!isset($lengthText)) {
return;
} else {
if ($lengthText == "SHORTS") {
// only match seconds, if the video has the shorts timestamp we can assume two things
// - the video is at MOST 1 minute
// - if it has no seconds in the accessibility label it is 100% exactly 1 minute long
preg_match("/([0-9]?[0-9])( seconds)|(1 second)/", $obj->title->accessibility->accessibilityData->label, $matches);
if (!isset($matches[0])) {
return "1:00";
} else {
$lengthText = (int) preg_replace("/( seconds)|( second)/", "", $matches[0]);
if ($lengthText < 10) {
return "0:0" . $lengthText;
} else {
return "0:" . $lengthText;
}
}
} else if ($lengthText == "LIVE") { // some endpoints have LIVE timestamp instead of badge
return null;
} else {
return $lengthText;
}
}
}
return null;
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register('getUrl', function($obj) {
return @$obj->navigationEndpoint->commandMetadata->webCommandMetadata->url
?? @$obj->navigationEndpoint->confirmDialogEndpoint->content->confirmDialogRenderer->confirmButton->buttonRenderer->command->urlEndpoint->url
?? @$obj->commandMetadata->webCommandMetadata->url
?? "";
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/**
* Helper function for finding the Watch Later button when building
* HTML templates.
*
* This iterates the overlays array and searches for how much of the
* video has been watched. If it's not present, this will return null.
*
* This is meant to be used as a helper function for Twig.
*
* @author Taniko Yamamoto <[email protected]>
* @author Aubrey Pankow <[email protected]>
*
* @param object $array of the thumbnail overlays
*
* @return ?object
*/
\Rehike\TemplateFunctions::register("getWatchedPercent", function($array) {
if (!isset($array->thumbnailOverlays )) return null;
foreach ($array->thumbnailOverlays as $index => $contents) {
if (isset($contents->thumbnailOverlayResumePlaybackRenderer)) {
return $contents->thumbnailOverlayResumePlaybackRenderer->percentDurationWatched;
}
}
// Return null if the index doesn't exist.
return null;
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register("getBadge", function($array, $name) {
if (null == $array) return;
for ($i = 0; $i < count($array); $i++) {
if (@$array[$i] ->metadataBadgeRenderer->style == $name) return $array[$i];
}
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register("getLockupInfo", function ($renderer) {
$response = (object) [];
// Get the name of the renderer
foreach($renderer as $key => $val) $rendName = $key;
$response->info = $renderer->$rendName;
$response->style = (strpos($rendName, "grid") > -1) ? "grid" : "tile";
$response->type = strtolower(str_replace("compact", "", str_replace("grid", "", str_replace("Renderer", "", $rendName))));
if ($a = @$response->info->thumbnails[0]) {
$response->thumbArray = $a;
} else if ($a = @$response->info->thumbnailRenderer->showCustomThumbnailRenderer->thumbnail) {
$response->thumbArray = $a;
} else {
$response->thumbArray = $response->info->thumbnail ?? null;
}
$validTypes = ["video", "channel", "playlist", "radio", "movie", "show"];
for ($i = 0; $i < count($validTypes); $i++) {
if ($response->type == $validTypes[$i]) {
return $response;
}
}
return null;
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register("resolveStyle", function($const) {
$styleOverrides = (object) [
"STYLE_BLUE_TEXT" => "STYLE_PRIMARY"
];
if (isset($styleOverrides->{$const})) {
$const = $styleOverrides->{$const};
}
return strtolower(str_replace(["STYLE_", "_"], ["", "-"], $const));
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register('getText', function ($obj) {
if (isset($obj->runs)) {
//return '';
$runs = $obj->runs;
$response = '';
for ($i = 0, $j = count($runs); $i < $j; $i++) {
$response .= $runs[$i]->text;
}
return $response;
} else if (isset($obj->simpleText)) {
return $obj->simpleText;
} else {
return '';
}
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register("getMeta", function ($renderer) {
$VALID_METAS = [
"viewCountText",
"publishedTimeText",
"videoCountText"
];
$metas = [];
foreach($VALID_METAS as $meta) {
if (isset($renderer->{$meta})
&& (
isset($renderer->{$meta} ->simpleText) ||
isset($renderer->{$meta} ->runs)
)) {
$metas[] = $renderer->{$meta};
}
}
return $metas;
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/**
* Helper function for finding thumbnail overlays.
*
* This iterates the overlays array and searches for the
* provided identifier.
*
* This is meant to be used as a helper function for Twig.
*
* @author Taniko Yamamoto <[email protected]>
*
* @param object $array of the thumbnail overlays
* @param string $name of the overlay identifier
*
* @return ?object
*/
\Rehike\TemplateFunctions::register("getThumbnailOverlay", function($array, $name)
{
if (!isset($array->thumbnailOverlays )) return null;
// Iterate the array and figure out the thumbnail overlay
foreach ($array->thumbnailOverlays as $index => $contents)
{
// InnerTube API formats thumbnail overlays as
// keys within an object. Fortunately, this is pretty
// easy to check within PHP.
if (isset($contents->$name)) return $contents->$name;
}
// Return null if the index doesn't exist.
return null;
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
\Rehike\TemplateFunctions::register("jsPath", function($name, $constants) {
return $constants->js->{$name} ?? "";
}); | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit14befcaebdd16793d803391aa69e5f63::getLoader();
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
Twig, the flexible, fast, and secure template language for PHP
==============================================================
Twig is a template language for PHP.
Twig uses a syntax similar to the Django and Jinja template languages which
inspired the Twig runtime environment.
Sponsors
--------
.. raw:: html
<a href="https://blackfire.io/docs/introduction?utm_source=twig&utm_medium=github_readme&utm_campaign=logo">
<img src="https://static.blackfire.io/assets/intemporals/logo/png/blackfire-io_secondary_horizontal_transparent.png?1" width="255px" alt="Blackfire.io">
</a>
More Information
----------------
Read the `documentation`_ for more information.
.. _documentation: https://twig.symfony.com/documentation
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
# 3.4.3 (2022-09-28)
* Fix a security issue on filesystem loader (possibility to load a template outside a configured directory)
# 3.4.2 (2022-08-12)
* Allow inherited magic method to still run with calling class
* Fix CallExpression::reflectCallable() throwing TypeError
* Fix typo in naming (currency_code)
# 3.4.1 (2022-05-17)
* Fix optimizing non-public named closures
# 3.4.0 (2022-05-22)
* Add support for named closures
# 3.3.10 (2022-04-06)
* Enable bytecode invalidation when auto_reload is enabled
# 3.3.9 (2022-03-25)
* Fix custom escapers when using multiple Twig environments
* Add support for "constant('class', object)"
* Do not reuse internally generated variable names during parsing
# 3.3.8 (2022-02-04)
* Fix a security issue when in a sandbox: the `sort` filter must require a Closure for the `arrow` parameter
* Fix deprecation notice on `round`
* Fix call to deprecated `convertToHtml` method
# 3.3.7 (2022-01-03)
* Allow more null support when Twig expects a string (for better 8.1 support)
* Only use Commonmark extensions if markdown enabled
# 3.3.6 (2022-01-03)
* Only use Commonmark extensions if markdown enabled
# 3.3.5 (2022-01-03)
* Allow CommonMark extensions to easily be added
* Allow null when Twig expects a string (for better 8.1 support)
* Make some performance optimizations
* Allow Symfony translation contract v3+
# 3.3.4 (2021-11-25)
* Bump minimum supported Symfony component versions
* Fix a deprecated message
# 3.3.3 (2021-09-17)
* Allow Symfony 6
* Improve compatibility with PHP 8.1
* Explicitly specify the encoding for mb_ord in JS escaper
# 3.3.2 (2021-05-16)
* Revert "Throw a proper exception when a template name is an absolute path (as it has never been supported)"
# 3.3.1 (2021-05-12)
* Fix PHP 8.1 compatibility
* Throw a proper exception when a template name is an absolute path (as it has never been supported)
# 3.3.0 (2021-02-08)
* Fix macro calls in a "cache" tag
* Add the slug filter
* Allow extra bundle to be compatible with Twig 2
# 3.2.1 (2021-01-05)
* Fix extra bundle compat with older versions of Symfony
# 3.2.0 (2021-01-05)
* Add the Cache extension in the "extra" repositories: "cache" tag
* Add "registerUndefinedTokenParserCallback"
* Mark built-in node visitors as @internal
* Fix "odd" not working for negative numbers
# 3.1.1 (2020-10-27)
* Fix "include(template_from_string())"
# 3.1.0 (2020-10-21)
* Fix sandbox support when using "include(template_from_string())"
* Make round brackets optional for one argument tests like "same as" or "divisible by"
* Add support for ES2015 style object initialisation shortcut { a } is the same as { 'a': a }
# 3.0.5 (2020-08-05)
* Fix twig_compare w.r.t. whitespace trimming
* Fix sandbox not disabled if syntax error occurs within {% sandbox %} tag
* Fix a regression when not using a space before an operator
* Restrict callables to closures in filters
* Allow trailing commas in argument lists (in calls as well as definitions)
# 3.0.4 (2020-07-05)
* Fix comparison operators
* Fix options not taken into account when using "Michelf\MarkdownExtra"
* Fix "Twig\Extra\Intl\IntlExtension::getCountryName()" to accept "null" as a first argument
* Throw exception in case non-Traversable data is passed to "filter"
* Fix context optimization on PHP 7.4
* Fix PHP 8 compatibility
* Fix ambiguous syntax parsing
# 3.0.3 (2020-02-11)
* Add a check to ensure that iconv() is defined
# 3.0.2 (2020-02-11)
* Avoid exceptions when an intl resource is not found
* Fix implementation of case-insensitivity for method names
# 3.0.1 (2019-12-28)
* fixed Symfony 5.0 support for the HTML extra extension
# 3.0.0 (2019-11-15)
* fixed number formatter in Intl extra extension when using a formatter prototype
# 3.0.0-BETA1 (2019-11-11)
* removed the "if" condition support on the "for" tag
* made the in, <, >, <=, >=, ==, and != operators more strict when comparing strings and integers/floats
* removed the "filter" tag
* added type hints everywhere
* changed Environment::resolveTemplate() to always return a TemplateWrapper instance
* removed Template::__toString()
* removed Parser::isReservedMacroName()
* removed SanboxedPrintNode
* removed Node::setTemplateName()
* made classes maked as "@final" final
* removed InitRuntimeInterface, ExistsLoaderInterface, and SourceContextLoaderInterface
* removed the "spaceless" tag
* removed Twig\Environment::getBaseTemplateClass() and Twig\Environment::setBaseTemplateClass()
* removed the "base_template_class" option on Twig\Environment
* bumped minimum PHP version to 7.2
* removed PSR-0 classes
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
name: "CI"
on:
pull_request:
push:
branches:
- '3.x'
env:
SYMFONY_PHPUNIT_DISABLE_RESULT_CACHE: 1
permissions:
contents: read
jobs:
tests:
name: "PHP ${{ matrix.php-version }}"
runs-on: 'ubuntu-latest'
continue-on-error: ${{ matrix.experimental }}
strategy:
matrix:
php-version:
- '7.2.5'
- '7.3'
- '7.4'
- '8.0'
- '8.1'
experimental: [false]
steps:
- name: "Checkout code"
uses: actions/checkout@v2
- name: "Install PHP with extensions"
uses: shivammathur/setup-php@v2
with:
coverage: "none"
php-version: ${{ matrix.php-version }}
ini-values: memory_limit=-1
- name: "Add PHPUnit matcher"
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- run: composer install
- name: "Install PHPUnit"
run: vendor/bin/simple-phpunit install
- name: "PHPUnit version"
run: vendor/bin/simple-phpunit --version
- name: "Run tests"
run: vendor/bin/simple-phpunit
extension-tests:
needs:
- 'tests'
name: "${{ matrix.extension }} with PHP ${{ matrix.php-version }}"
runs-on: 'ubuntu-latest'
continue-on-error: true
strategy:
matrix:
php-version:
- '7.2.5'
- '7.3'
- '7.4'
- '8.0'
- '8.1'
extension:
- 'extra/cache-extra'
- 'extra/cssinliner-extra'
- 'extra/html-extra'
- 'extra/inky-extra'
- 'extra/intl-extra'
- 'extra/markdown-extra'
- 'extra/string-extra'
- 'extra/twig-extra-bundle'
experimental: [false]
steps:
- name: "Checkout code"
uses: actions/checkout@v2
- name: "Install PHP with extensions"
uses: shivammathur/setup-php@v2
with:
coverage: "none"
php-version: ${{ matrix.php-version }}
ini-values: memory_limit=-1
- name: "Add PHPUnit matcher"
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- run: composer install
- name: "Install PHPUnit"
run: vendor/bin/simple-phpunit install
- name: "PHPUnit version"
run: vendor/bin/simple-phpunit --version
- name: "Composer install"
working-directory: ${{ matrix.extension}}
run: composer install
- name: "Run tests"
working-directory: ${{ matrix.extension}}
run: ../../vendor/bin/simple-phpunit
#
# Drupal does not support Twig 3 now!
#
# integration-tests:
# needs:
# - 'tests'
#
# name: "Integration tests with PHP ${{ matrix.php-version }}"
#
# runs-on: 'ubuntu-20.04'
#
# continue-on-error: true
#
# strategy:
# matrix:
# php-version:
# - '7.3'
#
# steps:
# - name: "Checkout code"
# uses: actions/checkout@v2
#
# - name: "Install PHP with extensions"
# uses: shivammathur/setup-php@2
# with:
# coverage: "none"
# extensions: "gd, pdo_sqlite"
# php-version: ${{ matrix.php-version }}
# ini-values: memory_limit=-1
# tools: composer:v2
#
# - run: bash ./tests/drupal_test.sh
# shell: "bash"
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
name: "Documentation"
on:
pull_request:
push:
branches:
- '2.x'
- '3.x'
permissions:
contents: read
jobs:
build:
name: "Build"
runs-on: ubuntu-latest
steps:
- name: "Checkout code"
uses: actions/checkout@v2
- name: "Set-up PHP"
uses: shivammathur/setup-php@v2
with:
php-version: 8.1
coverage: none
tools: "composer:v2"
- name: Get composer cache directory
id: composercache
working-directory: doc/_build
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
- name: Cache dependencies
uses: actions/cache@v2
with:
path: ${{ steps.composercache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-
- name: "Install dependencies"
working-directory: doc/_build
run: composer install --prefer-dist --no-progress
- name: "Build the docs"
working-directory: doc/_build
run: php build.php --disable-cache
doctor-rst:
name: "DOCtor-RST"
runs-on: ubuntu-latest
steps:
- name: "Checkout code"
uses: actions/checkout@v2
- name: "Run DOCtor-RST"
uses: docker://oskarstark/doctor-rst
with:
args: --short
env:
DOCS_DIR: 'doc/'
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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;
use Twig\Node\Expression\FunctionExpression;
use Twig\Node\Node;
/**
* Represents a template function.
*
* @author Fabien Potencier <[email protected]>
*
* @see https://twig.symfony.com/doc/templates.html#functions
*/
final class TwigFunction
{
private $name;
private $callable;
private $options;
private $arguments = [];
/**
* @param callable|null $callable A callable implementing the function. If null, you need to overwrite the "node_class" option to customize compilation.
*/
public function __construct(string $name, $callable = null, array $options = [])
{
$this->name = $name;
$this->callable = $callable;
$this->options = array_merge([
'needs_environment' => false,
'needs_context' => false,
'is_variadic' => false,
'is_safe' => null,
'is_safe_callback' => null,
'node_class' => FunctionExpression::class,
'deprecated' => false,
'alternative' => null,
], $options);
}
public function getName(): string
{
return $this->name;
}
/**
* Returns the callable to execute for this function.
*
* @return callable|null
*/
public function getCallable()
{
return $this->callable;
}
public function getNodeClass(): string
{
return $this->options['node_class'];
}
public function setArguments(array $arguments): void
{
$this->arguments = $arguments;
}
public function getArguments(): array
{
return $this->arguments;
}
public function needsEnvironment(): bool
{
return $this->options['needs_environment'];
}
public function needsContext(): bool
{
return $this->options['needs_context'];
}
public function getSafe(Node $functionArgs): ?array
{
if (null !== $this->options['is_safe']) {
return $this->options['is_safe'];
}
if (null !== $this->options['is_safe_callback']) {
return $this->options['is_safe_callback']($functionArgs);
}
return [];
}
public function isVariadic(): bool
{
return (bool) $this->options['is_variadic'];
}
public function isDeprecated(): bool
{
return (bool) $this->options['deprecated'];
}
public function getDeprecatedVersion(): string
{
return \is_bool($this->options['deprecated']) ? '' : $this->options['deprecated'];
}
public function getAlternative(): ?string
{
return $this->options['alternative'];
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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;
/**
* Holds information about a non-compiled Twig template.
*
* @author Fabien Potencier <[email protected]>
*/
final class Source
{
private $code;
private $name;
private $path;
/**
* @param string $code The template source code
* @param string $name The template logical name
* @param string $path The filesystem path of the template if any
*/
public function __construct(string $code, string $name, string $path = '')
{
$this->code = $code;
$this->name = $name;
$this->path = $path;
}
public function getCode(): string
{
return $this->code;
}
public function getName(): string
{
return $this->name;
}
public function getPath(): string
{
return $this->path;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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;
/**
* Marks a content as safe.
*
* @author Fabien Potencier <[email protected]>
*/
class Markup implements \Countable, \JsonSerializable
{
private $content;
private $charset;
public function __construct($content, $charset)
{
$this->content = (string) $content;
$this->charset = $charset;
}
public function __toString()
{
return $this->content;
}
/**
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
{
return mb_strlen($this->content, $this->charset);
}
/**
* @return mixed
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->content;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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;
/**
* Exposes a template to userland.
*
* @author Fabien Potencier <[email protected]>
*/
final class TemplateWrapper
{
private $env;
private $template;
/**
* This method is for internal use only and should never be called
* directly (use Twig\Environment::load() instead).
*
* @internal
*/
public function __construct(Environment $env, Template $template)
{
$this->env = $env;
$this->template = $template;
}
public function render(array $context = []): string
{
// using func_get_args() allows to not expose the blocks argument
// as it should only be used by internal code
return $this->template->render($context, \func_get_args()[1] ?? []);
}
public function display(array $context = [])
{
// using func_get_args() allows to not expose the blocks argument
// as it should only be used by internal code
$this->template->display($context, \func_get_args()[1] ?? []);
}
public function hasBlock(string $name, array $context = []): bool
{
return $this->template->hasBlock($name, $context);
}
/**
* @return string[] An array of defined template block names
*/
public function getBlockNames(array $context = []): array
{
return $this->template->getBlockNames($context);
}
public function renderBlock(string $name, array $context = []): string
{
$context = $this->env->mergeGlobals($context);
$level = ob_get_level();
if ($this->env->isDebug()) {
ob_start();
} else {
ob_start(function () { return ''; });
}
try {
$this->template->displayBlock($name, $context);
} catch (\Throwable $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}
throw $e;
}
return ob_get_clean();
}
public function displayBlock(string $name, array $context = [])
{
$this->template->displayBlock($name, $this->env->mergeGlobals($context));
}
public function getSourceContext(): Source
{
return $this->template->getSourceContext();
}
public function getTemplateName(): string
{
return $this->template->getTemplateName();
}
/**
* @internal
*
* @return Template
*/
public function unwrap()
{
return $this->template;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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;
use Twig\Node\Node;
use Twig\NodeVisitor\NodeVisitorInterface;
/**
* A node traverser.
*
* It visits all nodes and their children and calls the given visitor for each.
*
* @author Fabien Potencier <[email protected]>
*/
final class NodeTraverser
{
private $env;
private $visitors = [];
/**
* @param NodeVisitorInterface[] $visitors
*/
public function __construct(Environment $env, array $visitors = [])
{
$this->env = $env;
foreach ($visitors as $visitor) {
$this->addVisitor($visitor);
}
}
public function addVisitor(NodeVisitorInterface $visitor): void
{
$this->visitors[$visitor->getPriority()][] = $visitor;
}
/**
* Traverses a node and calls the registered visitors.
*/
public function traverse(Node $node): Node
{
ksort($this->visitors);
foreach ($this->visitors as $visitors) {
foreach ($visitors as $visitor) {
$node = $this->traverseForVisitor($visitor, $node);
}
}
return $node;
}
private function traverseForVisitor(NodeVisitorInterface $visitor, Node $node): ?Node
{
$node = $visitor->enterNode($node, $this->env);
foreach ($node as $k => $n) {
if (null !== $m = $this->traverseForVisitor($visitor, $n)) {
if ($m !== $n) {
$node->setNode($k, $m);
}
} else {
$node->removeNode($k);
}
}
return $visitor->leaveNode($node, $this->env);
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Node\Node;
/**
* @author Fabien Potencier <[email protected]>
*/
class Compiler
{
private $lastLine;
private $source;
private $indentation;
private $env;
private $debugInfo = [];
private $sourceOffset;
private $sourceLine;
private $varNameSalt = 0;
public function __construct(Environment $env)
{
$this->env = $env;
}
public function getEnvironment(): Environment
{
return $this->env;
}
public function getSource(): string
{
return $this->source;
}
/**
* @return $this
*/
public function compile(Node $node, int $indentation = 0)
{
$this->lastLine = null;
$this->source = '';
$this->debugInfo = [];
$this->sourceOffset = 0;
// source code starts at 1 (as we then increment it when we encounter new lines)
$this->sourceLine = 1;
$this->indentation = $indentation;
$this->varNameSalt = 0;
$node->compile($this);
return $this;
}
/**
* @return $this
*/
public function subcompile(Node $node, bool $raw = true)
{
if (false === $raw) {
$this->source .= str_repeat(' ', $this->indentation * 4);
}
$node->compile($this);
return $this;
}
/**
* Adds a raw string to the compiled code.
*
* @return $this
*/
public function raw(string $string)
{
$this->source .= $string;
return $this;
}
/**
* Writes a string to the compiled code by adding indentation.
*
* @return $this
*/
public function write(...$strings)
{
foreach ($strings as $string) {
$this->source .= str_repeat(' ', $this->indentation * 4).$string;
}
return $this;
}
/**
* Adds a quoted string to the compiled code.
*
* @return $this
*/
public function string(string $value)
{
$this->source .= sprintf('"%s"', addcslashes($value, "\0\t\"\$\\"));
return $this;
}
/**
* Returns a PHP representation of a given value.
*
* @return $this
*/
public function repr($value)
{
if (\is_int($value) || \is_float($value)) {
if (false !== $locale = setlocale(\LC_NUMERIC, '0')) {
setlocale(\LC_NUMERIC, 'C');
}
$this->raw(var_export($value, true));
if (false !== $locale) {
setlocale(\LC_NUMERIC, $locale);
}
} elseif (null === $value) {
$this->raw('null');
} elseif (\is_bool($value)) {
$this->raw($value ? 'true' : 'false');
} elseif (\is_array($value)) {
$this->raw('array(');
$first = true;
foreach ($value as $key => $v) {
if (!$first) {
$this->raw(', ');
}
$first = false;
$this->repr($key);
$this->raw(' => ');
$this->repr($v);
}
$this->raw(')');
} else {
$this->string($value);
}
return $this;
}
/**
* @return $this
*/
public function addDebugInfo(Node $node)
{
if ($node->getTemplateLine() != $this->lastLine) {
$this->write(sprintf("// line %d\n", $node->getTemplateLine()));
$this->sourceLine += substr_count($this->source, "\n", $this->sourceOffset);
$this->sourceOffset = \strlen($this->source);
$this->debugInfo[$this->sourceLine] = $node->getTemplateLine();
$this->lastLine = $node->getTemplateLine();
}
return $this;
}
public function getDebugInfo(): array
{
ksort($this->debugInfo);
return $this->debugInfo;
}
/**
* @return $this
*/
public function indent(int $step = 1)
{
$this->indentation += $step;
return $this;
}
/**
* @return $this
*
* @throws \LogicException When trying to outdent too much so the indentation would become negative
*/
public function outdent(int $step = 1)
{
// can't outdent by more steps than the current indentation level
if ($this->indentation < $step) {
throw new \LogicException('Unable to call outdent() as the indentation would become negative.');
}
$this->indentation -= $step;
return $this;
}
public function getVarName(): string
{
return sprintf('__internal_compile_%d', $this->varNameSalt++);
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\Error;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
/**
* Default base class for compiled templates.
*
* This class is an implementation detail of how template compilation currently
* works, which might change. It should never be used directly. Use $twig->load()
* instead, which returns an instance of \Twig\TemplateWrapper.
*
* @author Fabien Potencier <[email protected]>
*
* @internal
*/
abstract class Template
{
public const ANY_CALL = 'any';
public const ARRAY_CALL = 'array';
public const METHOD_CALL = 'method';
protected $parent;
protected $parents = [];
protected $env;
protected $blocks = [];
protected $traits = [];
protected $extensions = [];
protected $sandbox;
public function __construct(Environment $env)
{
$this->env = $env;
$this->extensions = $env->getExtensions();
}
/**
* Returns the template name.
*
* @return string The template name
*/
abstract public function getTemplateName();
/**
* Returns debug information about the template.
*
* @return array Debug information
*/
abstract public function getDebugInfo();
/**
* Returns information about the original template source code.
*
* @return Source
*/
abstract public function getSourceContext();
/**
* Returns the parent template.
*
* This method is for internal use only and should never be called
* directly.
*
* @return Template|TemplateWrapper|false The parent template or false if there is no parent
*/
public function getParent(array $context)
{
if (null !== $this->parent) {
return $this->parent;
}
try {
$parent = $this->doGetParent($context);
if (false === $parent) {
return false;
}
if ($parent instanceof self || $parent instanceof TemplateWrapper) {
return $this->parents[$parent->getSourceContext()->getName()] = $parent;
}
if (!isset($this->parents[$parent])) {
$this->parents[$parent] = $this->loadTemplate($parent);
}
} catch (LoaderError $e) {
$e->setSourceContext(null);
$e->guess();
throw $e;
}
return $this->parents[$parent];
}
protected function doGetParent(array $context)
{
return false;
}
public function isTraitable()
{
return true;
}
/**
* Displays a parent block.
*
* This method is for internal use only and should never be called
* directly.
*
* @param string $name The block name to display from the parent
* @param array $context The context
* @param array $blocks The current set of blocks
*/
public function displayParentBlock($name, array $context, array $blocks = [])
{
if (isset($this->traits[$name])) {
$this->traits[$name][0]->displayBlock($name, $context, $blocks, false);
} elseif (false !== $parent = $this->getParent($context)) {
$parent->displayBlock($name, $context, $blocks, false);
} else {
throw new RuntimeError(sprintf('The template has no parent and no traits defining the "%s" block.', $name), -1, $this->getSourceContext());
}
}
/**
* Displays a block.
*
* This method is for internal use only and should never be called
* directly.
*
* @param string $name The block name to display
* @param array $context The context
* @param array $blocks The current set of blocks
* @param bool $useBlocks Whether to use the current set of blocks
*/
public function displayBlock($name, array $context, array $blocks = [], $useBlocks = true, self $templateContext = null)
{
if ($useBlocks && isset($blocks[$name])) {
$template = $blocks[$name][0];
$block = $blocks[$name][1];
} elseif (isset($this->blocks[$name])) {
$template = $this->blocks[$name][0];
$block = $this->blocks[$name][1];
} else {
$template = null;
$block = null;
}
// avoid RCEs when sandbox is enabled
if (null !== $template && !$template instanceof self) {
throw new \LogicException('A block must be a method on a \Twig\Template instance.');
}
if (null !== $template) {
try {
$template->$block($context, $blocks);
} catch (Error $e) {
if (!$e->getSourceContext()) {
$e->setSourceContext($template->getSourceContext());
}
// this is mostly useful for \Twig\Error\LoaderError exceptions
// see \Twig\Error\LoaderError
if (-1 === $e->getTemplateLine()) {
$e->guess();
}
throw $e;
} catch (\Exception $e) {
$e = new RuntimeError(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $template->getSourceContext(), $e);
$e->guess();
throw $e;
}
} elseif (false !== $parent = $this->getParent($context)) {
$parent->displayBlock($name, $context, array_merge($this->blocks, $blocks), false, $templateContext ?? $this);
} elseif (isset($blocks[$name])) {
throw new RuntimeError(sprintf('Block "%s" should not call parent() in "%s" as the block does not exist in the parent template "%s".', $name, $blocks[$name][0]->getTemplateName(), $this->getTemplateName()), -1, $blocks[$name][0]->getSourceContext());
} else {
throw new RuntimeError(sprintf('Block "%s" on template "%s" does not exist.', $name, $this->getTemplateName()), -1, ($templateContext ?? $this)->getSourceContext());
}
}
/**
* Renders a parent block.
*
* This method is for internal use only and should never be called
* directly.
*
* @param string $name The block name to render from the parent
* @param array $context The context
* @param array $blocks The current set of blocks
*
* @return string The rendered block
*/
public function renderParentBlock($name, array $context, array $blocks = [])
{
if ($this->env->isDebug()) {
ob_start();
} else {
ob_start(function () { return ''; });
}
$this->displayParentBlock($name, $context, $blocks);
return ob_get_clean();
}
/**
* Renders a block.
*
* This method is for internal use only and should never be called
* directly.
*
* @param string $name The block name to render
* @param array $context The context
* @param array $blocks The current set of blocks
* @param bool $useBlocks Whether to use the current set of blocks
*
* @return string The rendered block
*/
public function renderBlock($name, array $context, array $blocks = [], $useBlocks = true)
{
if ($this->env->isDebug()) {
ob_start();
} else {
ob_start(function () { return ''; });
}
$this->displayBlock($name, $context, $blocks, $useBlocks);
return ob_get_clean();
}
/**
* Returns whether a block exists or not in the current context of the template.
*
* This method checks blocks defined in the current template
* or defined in "used" traits or defined in parent templates.
*
* @param string $name The block name
* @param array $context The context
* @param array $blocks The current set of blocks
*
* @return bool true if the block exists, false otherwise
*/
public function hasBlock($name, array $context, array $blocks = [])
{
if (isset($blocks[$name])) {
return $blocks[$name][0] instanceof self;
}
if (isset($this->blocks[$name])) {
return true;
}
if (false !== $parent = $this->getParent($context)) {
return $parent->hasBlock($name, $context);
}
return false;
}
/**
* Returns all block names in the current context of the template.
*
* This method checks blocks defined in the current template
* or defined in "used" traits or defined in parent templates.
*
* @param array $context The context
* @param array $blocks The current set of blocks
*
* @return array An array of block names
*/
public function getBlockNames(array $context, array $blocks = [])
{
$names = array_merge(array_keys($blocks), array_keys($this->blocks));
if (false !== $parent = $this->getParent($context)) {
$names = array_merge($names, $parent->getBlockNames($context));
}
return array_unique($names);
}
/**
* @return Template|TemplateWrapper
*/
protected function loadTemplate($template, $templateName = null, $line = null, $index = null)
{
try {
if (\is_array($template)) {
return $this->env->resolveTemplate($template);
}
if ($template instanceof self || $template instanceof TemplateWrapper) {
return $template;
}
if ($template === $this->getTemplateName()) {
$class = static::class;
if (false !== $pos = strrpos($class, '___', -1)) {
$class = substr($class, 0, $pos);
}
} else {
$class = $this->env->getTemplateClass($template);
}
return $this->env->loadTemplate($class, $template, $index);
} catch (Error $e) {
if (!$e->getSourceContext()) {
$e->setSourceContext($templateName ? new Source('', $templateName) : $this->getSourceContext());
}
if ($e->getTemplateLine() > 0) {
throw $e;
}
if (!$line) {
$e->guess();
} else {
$e->setTemplateLine($line);
}
throw $e;
}
}
/**
* @internal
*
* @return Template
*/
public function unwrap()
{
return $this;
}
/**
* Returns all blocks.
*
* This method is for internal use only and should never be called
* directly.
*
* @return array An array of blocks
*/
public function getBlocks()
{
return $this->blocks;
}
public function display(array $context, array $blocks = [])
{
$this->displayWithErrorHandling($this->env->mergeGlobals($context), array_merge($this->blocks, $blocks));
}
public function render(array $context)
{
$level = ob_get_level();
if ($this->env->isDebug()) {
ob_start();
} else {
ob_start(function () { return ''; });
}
try {
$this->display($context);
} catch (\Throwable $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}
throw $e;
}
return ob_get_clean();
}
protected function displayWithErrorHandling(array $context, array $blocks = [])
{
try {
$this->doDisplay($context, $blocks);
} catch (Error $e) {
if (!$e->getSourceContext()) {
$e->setSourceContext($this->getSourceContext());
}
// this is mostly useful for \Twig\Error\LoaderError exceptions
// see \Twig\Error\LoaderError
if (-1 === $e->getTemplateLine()) {
$e->guess();
}
throw $e;
} catch (\Exception $e) {
$e = new RuntimeError(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $this->getSourceContext(), $e);
$e->guess();
throw $e;
}
}
/**
* Auto-generated method to display the template with the given context.
*
* @param array $context An array of parameters to pass to the template
* @param array $blocks An array of blocks to pass to the template
*/
abstract protected function doDisplay(array $context, array $blocks = []);
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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;
use Twig\Error\RuntimeError;
use Twig\Extension\ExtensionInterface;
use Twig\Extension\GlobalsInterface;
use Twig\Extension\StagingExtension;
use Twig\NodeVisitor\NodeVisitorInterface;
use Twig\TokenParser\TokenParserInterface;
/**
* @author Fabien Potencier <[email protected]>
*
* @internal
*/
final class ExtensionSet
{
private $extensions;
private $initialized = false;
private $runtimeInitialized = false;
private $staging;
private $parsers;
private $visitors;
private $filters;
private $tests;
private $functions;
private $unaryOperators;
private $binaryOperators;
private $globals;
private $functionCallbacks = [];
private $filterCallbacks = [];
private $parserCallbacks = [];
private $lastModified = 0;
public function __construct()
{
$this->staging = new StagingExtension();
}
public function initRuntime()
{
$this->runtimeInitialized = true;
}
public function hasExtension(string $class): bool
{
return isset($this->extensions[ltrim($class, '\\')]);
}
public function getExtension(string $class): ExtensionInterface
{
$class = ltrim($class, '\\');
if (!isset($this->extensions[$class])) {
throw new RuntimeError(sprintf('The "%s" extension is not enabled.', $class));
}
return $this->extensions[$class];
}
/**
* @param ExtensionInterface[] $extensions
*/
public function setExtensions(array $extensions): void
{
foreach ($extensions as $extension) {
$this->addExtension($extension);
}
}
/**
* @return ExtensionInterface[]
*/
public function getExtensions(): array
{
return $this->extensions;
}
public function getSignature(): string
{
return json_encode(array_keys($this->extensions));
}
public function isInitialized(): bool
{
return $this->initialized || $this->runtimeInitialized;
}
public function getLastModified(): int
{
if (0 !== $this->lastModified) {
return $this->lastModified;
}
foreach ($this->extensions as $extension) {
$r = new \ReflectionObject($extension);
if (is_file($r->getFileName()) && ($extensionTime = filemtime($r->getFileName())) > $this->lastModified) {
$this->lastModified = $extensionTime;
}
}
return $this->lastModified;
}
public function addExtension(ExtensionInterface $extension): void
{
$class = \get_class($extension);
if ($this->initialized) {
throw new \LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $class));
}
if (isset($this->extensions[$class])) {
throw new \LogicException(sprintf('Unable to register extension "%s" as it is already registered.', $class));
}
$this->extensions[$class] = $extension;
}
public function addFunction(TwigFunction $function): void
{
if ($this->initialized) {
throw new \LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $function->getName()));
}
$this->staging->addFunction($function);
}
/**
* @return TwigFunction[]
*/
public function getFunctions(): array
{
if (!$this->initialized) {
$this->initExtensions();
}
return $this->functions;
}
public function getFunction(string $name): ?TwigFunction
{
if (!$this->initialized) {
$this->initExtensions();
}
if (isset($this->functions[$name])) {
return $this->functions[$name];
}
foreach ($this->functions as $pattern => $function) {
$pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count);
if ($count && preg_match('#^'.$pattern.'$#', $name, $matches)) {
array_shift($matches);
$function->setArguments($matches);
return $function;
}
}
foreach ($this->functionCallbacks as $callback) {
if (false !== $function = $callback($name)) {
return $function;
}
}
return null;
}
public function registerUndefinedFunctionCallback(callable $callable): void
{
$this->functionCallbacks[] = $callable;
}
public function addFilter(TwigFilter $filter): void
{
if ($this->initialized) {
throw new \LogicException(sprintf('Unable to add filter "%s" as extensions have already been initialized.', $filter->getName()));
}
$this->staging->addFilter($filter);
}
/**
* @return TwigFilter[]
*/
public function getFilters(): array
{
if (!$this->initialized) {
$this->initExtensions();
}
return $this->filters;
}
public function getFilter(string $name): ?TwigFilter
{
if (!$this->initialized) {
$this->initExtensions();
}
if (isset($this->filters[$name])) {
return $this->filters[$name];
}
foreach ($this->filters as $pattern => $filter) {
$pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count);
if ($count && preg_match('#^'.$pattern.'$#', $name, $matches)) {
array_shift($matches);
$filter->setArguments($matches);
return $filter;
}
}
foreach ($this->filterCallbacks as $callback) {
if (false !== $filter = $callback($name)) {
return $filter;
}
}
return null;
}
public function registerUndefinedFilterCallback(callable $callable): void
{
$this->filterCallbacks[] = $callable;
}
public function addNodeVisitor(NodeVisitorInterface $visitor): void
{
if ($this->initialized) {
throw new \LogicException('Unable to add a node visitor as extensions have already been initialized.');
}
$this->staging->addNodeVisitor($visitor);
}
/**
* @return NodeVisitorInterface[]
*/
public function getNodeVisitors(): array
{
if (!$this->initialized) {
$this->initExtensions();
}
return $this->visitors;
}
public function addTokenParser(TokenParserInterface $parser): void
{
if ($this->initialized) {
throw new \LogicException('Unable to add a token parser as extensions have already been initialized.');
}
$this->staging->addTokenParser($parser);
}
/**
* @return TokenParserInterface[]
*/
public function getTokenParsers(): array
{
if (!$this->initialized) {
$this->initExtensions();
}
return $this->parsers;
}
public function getTokenParser(string $name): ?TokenParserInterface
{
if (!$this->initialized) {
$this->initExtensions();
}
if (isset($this->parsers[$name])) {
return $this->parsers[$name];
}
foreach ($this->parserCallbacks as $callback) {
if (false !== $parser = $callback($name)) {
return $parser;
}
}
return null;
}
public function registerUndefinedTokenParserCallback(callable $callable): void
{
$this->parserCallbacks[] = $callable;
}
public function getGlobals(): array
{
if (null !== $this->globals) {
return $this->globals;
}
$globals = [];
foreach ($this->extensions as $extension) {
if (!$extension instanceof GlobalsInterface) {
continue;
}
$extGlobals = $extension->getGlobals();
if (!\is_array($extGlobals)) {
throw new \UnexpectedValueException(sprintf('"%s::getGlobals()" must return an array of globals.', \get_class($extension)));
}
$globals = array_merge($globals, $extGlobals);
}
if ($this->initialized) {
$this->globals = $globals;
}
return $globals;
}
public function addTest(TwigTest $test): void
{
if ($this->initialized) {
throw new \LogicException(sprintf('Unable to add test "%s" as extensions have already been initialized.', $test->getName()));
}
$this->staging->addTest($test);
}
/**
* @return TwigTest[]
*/
public function getTests(): array
{
if (!$this->initialized) {
$this->initExtensions();
}
return $this->tests;
}
public function getTest(string $name): ?TwigTest
{
if (!$this->initialized) {
$this->initExtensions();
}
if (isset($this->tests[$name])) {
return $this->tests[$name];
}
foreach ($this->tests as $pattern => $test) {
$pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count);
if ($count) {
if (preg_match('#^'.$pattern.'$#', $name, $matches)) {
array_shift($matches);
$test->setArguments($matches);
return $test;
}
}
}
return null;
}
public function getUnaryOperators(): array
{
if (!$this->initialized) {
$this->initExtensions();
}
return $this->unaryOperators;
}
public function getBinaryOperators(): array
{
if (!$this->initialized) {
$this->initExtensions();
}
return $this->binaryOperators;
}
private function initExtensions(): void
{
$this->parsers = [];
$this->filters = [];
$this->functions = [];
$this->tests = [];
$this->visitors = [];
$this->unaryOperators = [];
$this->binaryOperators = [];
foreach ($this->extensions as $extension) {
$this->initExtension($extension);
}
$this->initExtension($this->staging);
// Done at the end only, so that an exception during initialization does not mark the environment as initialized when catching the exception
$this->initialized = true;
}
private function initExtension(ExtensionInterface $extension): void
{
// filters
foreach ($extension->getFilters() as $filter) {
$this->filters[$filter->getName()] = $filter;
}
// functions
foreach ($extension->getFunctions() as $function) {
$this->functions[$function->getName()] = $function;
}
// tests
foreach ($extension->getTests() as $test) {
$this->tests[$test->getName()] = $test;
}
// token parsers
foreach ($extension->getTokenParsers() as $parser) {
if (!$parser instanceof TokenParserInterface) {
throw new \LogicException('getTokenParsers() must return an array of \Twig\TokenParser\TokenParserInterface.');
}
$this->parsers[$parser->getTag()] = $parser;
}
// node visitors
foreach ($extension->getNodeVisitors() as $visitor) {
$this->visitors[] = $visitor;
}
// operators
if ($operators = $extension->getOperators()) {
if (!\is_array($operators)) {
throw new \InvalidArgumentException(sprintf('"%s::getOperators()" must return an array with operators, got "%s".', \get_class($extension), \is_object($operators) ? \get_class($operators) : \gettype($operators).(\is_resource($operators) ? '' : '#'.$operators)));
}
if (2 !== \count($operators)) {
throw new \InvalidArgumentException(sprintf('"%s::getOperators()" must return an array of 2 elements, got %d.', \get_class($extension), \count($operators)));
}
$this->unaryOperators = array_merge($this->unaryOperators, $operators[0]);
$this->binaryOperators = array_merge($this->binaryOperators, $operators[1]);
}
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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;
/**
* Default autoescaping strategy based on file names.
*
* This strategy sets the HTML as the default autoescaping strategy,
* but changes it based on the template name.
*
* Note that there is no runtime performance impact as the
* default autoescaping strategy is set at compilation time.
*
* @author Fabien Potencier <[email protected]>
*/
class FileExtensionEscapingStrategy
{
/**
* Guesses the best autoescaping strategy based on the file name.
*
* @param string $name The template name
*
* @return string|false The escaping strategy name to use or false to disable
*/
public static function guess(string $name)
{
if (\in_array(substr($name, -1), ['/', '\\'])) {
return 'html'; // return html for directories
}
if ('.twig' === substr($name, -5)) {
$name = substr($name, 0, -5);
}
$extension = pathinfo($name, \PATHINFO_EXTENSION);
switch ($extension) {
case 'js':
return 'js';
case 'css':
return 'css';
case 'txt':
return false;
default:
return 'html';
}
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\SyntaxError;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\ArrayExpression;
use Twig\Node\Expression\ArrowFunctionExpression;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\Expression\Binary\ConcatBinary;
use Twig\Node\Expression\BlockReferenceExpression;
use Twig\Node\Expression\ConditionalExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\MethodCallExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Expression\ParentExpression;
use Twig\Node\Expression\TestExpression;
use Twig\Node\Expression\Unary\NegUnary;
use Twig\Node\Expression\Unary\NotUnary;
use Twig\Node\Expression\Unary\PosUnary;
use Twig\Node\Node;
/**
* Parses expressions.
*
* This parser implements a "Precedence climbing" algorithm.
*
* @see https://www.engr.mun.ca/~theo/Misc/exp_parsing.htm
* @see https://en.wikipedia.org/wiki/Operator-precedence_parser
*
* @author Fabien Potencier <[email protected]>
*
* @internal
*/
class ExpressionParser
{
public const OPERATOR_LEFT = 1;
public const OPERATOR_RIGHT = 2;
private $parser;
private $env;
private $unaryOperators;
private $binaryOperators;
public function __construct(Parser $parser, Environment $env)
{
$this->parser = $parser;
$this->env = $env;
$this->unaryOperators = $env->getUnaryOperators();
$this->binaryOperators = $env->getBinaryOperators();
}
public function parseExpression($precedence = 0, $allowArrow = false)
{
if ($allowArrow && $arrow = $this->parseArrow()) {
return $arrow;
}
$expr = $this->getPrimary();
$token = $this->parser->getCurrentToken();
while ($this->isBinary($token) && $this->binaryOperators[$token->getValue()]['precedence'] >= $precedence) {
$op = $this->binaryOperators[$token->getValue()];
$this->parser->getStream()->next();
if ('is not' === $token->getValue()) {
$expr = $this->parseNotTestExpression($expr);
} elseif ('is' === $token->getValue()) {
$expr = $this->parseTestExpression($expr);
} elseif (isset($op['callable'])) {
$expr = $op['callable']($this->parser, $expr);
} else {
$expr1 = $this->parseExpression(self::OPERATOR_LEFT === $op['associativity'] ? $op['precedence'] + 1 : $op['precedence']);
$class = $op['class'];
$expr = new $class($expr, $expr1, $token->getLine());
}
$token = $this->parser->getCurrentToken();
}
if (0 === $precedence) {
return $this->parseConditionalExpression($expr);
}
return $expr;
}
/**
* @return ArrowFunctionExpression|null
*/
private function parseArrow()
{
$stream = $this->parser->getStream();
// short array syntax (one argument, no parentheses)?
if ($stream->look(1)->test(/* Token::ARROW_TYPE */ 12)) {
$line = $stream->getCurrent()->getLine();
$token = $stream->expect(/* Token::NAME_TYPE */ 5);
$names = [new AssignNameExpression($token->getValue(), $token->getLine())];
$stream->expect(/* Token::ARROW_TYPE */ 12);
return new ArrowFunctionExpression($this->parseExpression(0), new Node($names), $line);
}
// first, determine if we are parsing an arrow function by finding => (long form)
$i = 0;
if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
return null;
}
++$i;
while (true) {
// variable name
++$i;
if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
break;
}
++$i;
}
if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, ')')) {
return null;
}
++$i;
if (!$stream->look($i)->test(/* Token::ARROW_TYPE */ 12)) {
return null;
}
// yes, let's parse it properly
$token = $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '(');
$line = $token->getLine();
$names = [];
while (true) {
$token = $stream->expect(/* Token::NAME_TYPE */ 5);
$names[] = new AssignNameExpression($token->getValue(), $token->getLine());
if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
break;
}
}
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ')');
$stream->expect(/* Token::ARROW_TYPE */ 12);
return new ArrowFunctionExpression($this->parseExpression(0), new Node($names), $line);
}
private function getPrimary(): AbstractExpression
{
$token = $this->parser->getCurrentToken();
if ($this->isUnary($token)) {
$operator = $this->unaryOperators[$token->getValue()];
$this->parser->getStream()->next();
$expr = $this->parseExpression($operator['precedence']);
$class = $operator['class'];
return $this->parsePostfixExpression(new $class($expr, $token->getLine()));
} elseif ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
$this->parser->getStream()->next();
$expr = $this->parseExpression();
$this->parser->getStream()->expect(/* Token::PUNCTUATION_TYPE */ 9, ')', 'An opened parenthesis is not properly closed');
return $this->parsePostfixExpression($expr);
}
return $this->parsePrimaryExpression();
}
private function parseConditionalExpression($expr): AbstractExpression
{
while ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, '?')) {
if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
$expr2 = $this->parseExpression();
if ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
$expr3 = $this->parseExpression();
} else {
$expr3 = new ConstantExpression('', $this->parser->getCurrentToken()->getLine());
}
} else {
$expr2 = $expr;
$expr3 = $this->parseExpression();
}
$expr = new ConditionalExpression($expr, $expr2, $expr3, $this->parser->getCurrentToken()->getLine());
}
return $expr;
}
private function isUnary(Token $token): bool
{
return $token->test(/* Token::OPERATOR_TYPE */ 8) && isset($this->unaryOperators[$token->getValue()]);
}
private function isBinary(Token $token): bool
{
return $token->test(/* Token::OPERATOR_TYPE */ 8) && isset($this->binaryOperators[$token->getValue()]);
}
public function parsePrimaryExpression()
{
$token = $this->parser->getCurrentToken();
switch ($token->getType()) {
case /* Token::NAME_TYPE */ 5:
$this->parser->getStream()->next();
switch ($token->getValue()) {
case 'true':
case 'TRUE':
$node = new ConstantExpression(true, $token->getLine());
break;
case 'false':
case 'FALSE':
$node = new ConstantExpression(false, $token->getLine());
break;
case 'none':
case 'NONE':
case 'null':
case 'NULL':
$node = new ConstantExpression(null, $token->getLine());
break;
default:
if ('(' === $this->parser->getCurrentToken()->getValue()) {
$node = $this->getFunctionNode($token->getValue(), $token->getLine());
} else {
$node = new NameExpression($token->getValue(), $token->getLine());
}
}
break;
case /* Token::NUMBER_TYPE */ 6:
$this->parser->getStream()->next();
$node = new ConstantExpression($token->getValue(), $token->getLine());
break;
case /* Token::STRING_TYPE */ 7:
case /* Token::INTERPOLATION_START_TYPE */ 10:
$node = $this->parseStringExpression();
break;
case /* Token::OPERATOR_TYPE */ 8:
if (preg_match(Lexer::REGEX_NAME, $token->getValue(), $matches) && $matches[0] == $token->getValue()) {
// in this context, string operators are variable names
$this->parser->getStream()->next();
$node = new NameExpression($token->getValue(), $token->getLine());
break;
}
if (isset($this->unaryOperators[$token->getValue()])) {
$class = $this->unaryOperators[$token->getValue()]['class'];
if (!\in_array($class, [NegUnary::class, PosUnary::class])) {
throw new SyntaxError(sprintf('Unexpected unary operator "%s".', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());
}
$this->parser->getStream()->next();
$expr = $this->parsePrimaryExpression();
$node = new $class($expr, $token->getLine());
break;
}
// no break
default:
if ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '[')) {
$node = $this->parseArrayExpression();
} elseif ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '{')) {
$node = $this->parseHashExpression();
} elseif ($token->test(/* Token::OPERATOR_TYPE */ 8, '=') && ('==' === $this->parser->getStream()->look(-1)->getValue() || '!=' === $this->parser->getStream()->look(-1)->getValue())) {
throw new SyntaxError(sprintf('Unexpected operator of value "%s". Did you try to use "===" or "!==" for strict comparison? Use "is same as(value)" instead.', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());
} else {
throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s".', Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());
}
}
return $this->parsePostfixExpression($node);
}
public function parseStringExpression()
{
$stream = $this->parser->getStream();
$nodes = [];
// a string cannot be followed by another string in a single expression
$nextCanBeString = true;
while (true) {
if ($nextCanBeString && $token = $stream->nextIf(/* Token::STRING_TYPE */ 7)) {
$nodes[] = new ConstantExpression($token->getValue(), $token->getLine());
$nextCanBeString = false;
} elseif ($stream->nextIf(/* Token::INTERPOLATION_START_TYPE */ 10)) {
$nodes[] = $this->parseExpression();
$stream->expect(/* Token::INTERPOLATION_END_TYPE */ 11);
$nextCanBeString = true;
} else {
break;
}
}
$expr = array_shift($nodes);
foreach ($nodes as $node) {
$expr = new ConcatBinary($expr, $node, $node->getTemplateLine());
}
return $expr;
}
public function parseArrayExpression()
{
$stream = $this->parser->getStream();
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '[', 'An array element was expected');
$node = new ArrayExpression([], $stream->getCurrent()->getLine());
$first = true;
while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) {
if (!$first) {
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'An array element must be followed by a comma');
// trailing ,?
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) {
break;
}
}
$first = false;
$node->addElement($this->parseExpression());
}
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']', 'An opened array is not properly closed');
return $node;
}
public function parseHashExpression()
{
$stream = $this->parser->getStream();
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '{', 'A hash element was expected');
$node = new ArrayExpression([], $stream->getCurrent()->getLine());
$first = true;
while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, '}')) {
if (!$first) {
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'A hash value must be followed by a comma');
// trailing ,?
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '}')) {
break;
}
}
$first = false;
// a hash key can be:
//
// * a number -- 12
// * a string -- 'a'
// * a name, which is equivalent to a string -- a
// * an expression, which must be enclosed in parentheses -- (1 + 2)
if ($token = $stream->nextIf(/* Token::NAME_TYPE */ 5)) {
$key = new ConstantExpression($token->getValue(), $token->getLine());
// {a} is a shortcut for {a:a}
if ($stream->test(Token::PUNCTUATION_TYPE, [',', '}'])) {
$value = new NameExpression($key->getAttribute('value'), $key->getTemplateLine());
$node->addElement($value, $key);
continue;
}
} elseif (($token = $stream->nextIf(/* Token::STRING_TYPE */ 7)) || $token = $stream->nextIf(/* Token::NUMBER_TYPE */ 6)) {
$key = new ConstantExpression($token->getValue(), $token->getLine());
} elseif ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
$key = $this->parseExpression();
} else {
$current = $stream->getCurrent();
throw new SyntaxError(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s".', Token::typeToEnglish($current->getType()), $current->getValue()), $current->getLine(), $stream->getSourceContext());
}
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ':', 'A hash key must be followed by a colon (:)');
$value = $this->parseExpression();
$node->addElement($value, $key);
}
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '}', 'An opened hash is not properly closed');
return $node;
}
public function parsePostfixExpression($node)
{
while (true) {
$token = $this->parser->getCurrentToken();
if (/* Token::PUNCTUATION_TYPE */ 9 == $token->getType()) {
if ('.' == $token->getValue() || '[' == $token->getValue()) {
$node = $this->parseSubscriptExpression($node);
} elseif ('|' == $token->getValue()) {
$node = $this->parseFilterExpression($node);
} else {
break;
}
} else {
break;
}
}
return $node;
}
public function getFunctionNode($name, $line)
{
switch ($name) {
case 'parent':
$this->parseArguments();
if (!\count($this->parser->getBlockStack())) {
throw new SyntaxError('Calling "parent" outside a block is forbidden.', $line, $this->parser->getStream()->getSourceContext());
}
if (!$this->parser->getParent() && !$this->parser->hasTraits()) {
throw new SyntaxError('Calling "parent" on a template that does not extend nor "use" another template is forbidden.', $line, $this->parser->getStream()->getSourceContext());
}
return new ParentExpression($this->parser->peekBlockStack(), $line);
case 'block':
$args = $this->parseArguments();
if (\count($args) < 1) {
throw new SyntaxError('The "block" function takes one argument (the block name).', $line, $this->parser->getStream()->getSourceContext());
}
return new BlockReferenceExpression($args->getNode(0), \count($args) > 1 ? $args->getNode(1) : null, $line);
case 'attribute':
$args = $this->parseArguments();
if (\count($args) < 2) {
throw new SyntaxError('The "attribute" function takes at least two arguments (the variable and the attributes).', $line, $this->parser->getStream()->getSourceContext());
}
return new GetAttrExpression($args->getNode(0), $args->getNode(1), \count($args) > 2 ? $args->getNode(2) : null, Template::ANY_CALL, $line);
default:
if (null !== $alias = $this->parser->getImportedSymbol('function', $name)) {
$arguments = new ArrayExpression([], $line);
foreach ($this->parseArguments() as $n) {
$arguments->addElement($n);
}
$node = new MethodCallExpression($alias['node'], $alias['name'], $arguments, $line);
$node->setAttribute('safe', true);
return $node;
}
$args = $this->parseArguments(true);
$class = $this->getFunctionNodeClass($name, $line);
return new $class($name, $args, $line);
}
}
public function parseSubscriptExpression($node)
{
$stream = $this->parser->getStream();
$token = $stream->next();
$lineno = $token->getLine();
$arguments = new ArrayExpression([], $lineno);
$type = Template::ANY_CALL;
if ('.' == $token->getValue()) {
$token = $stream->next();
if (
/* Token::NAME_TYPE */ 5 == $token->getType()
||
/* Token::NUMBER_TYPE */ 6 == $token->getType()
||
(/* Token::OPERATOR_TYPE */ 8 == $token->getType() && preg_match(Lexer::REGEX_NAME, $token->getValue()))
) {
$arg = new ConstantExpression($token->getValue(), $lineno);
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
$type = Template::METHOD_CALL;
foreach ($this->parseArguments() as $n) {
$arguments->addElement($n);
}
}
} else {
throw new SyntaxError(sprintf('Expected name or number, got value "%s" of type %s.', $token->getValue(), Token::typeToEnglish($token->getType())), $lineno, $stream->getSourceContext());
}
if ($node instanceof NameExpression && null !== $this->parser->getImportedSymbol('template', $node->getAttribute('name'))) {
if (!$arg instanceof ConstantExpression) {
throw new SyntaxError(sprintf('Dynamic macro names are not supported (called on "%s").', $node->getAttribute('name')), $token->getLine(), $stream->getSourceContext());
}
$name = $arg->getAttribute('value');
$node = new MethodCallExpression($node, 'macro_'.$name, $arguments, $lineno);
$node->setAttribute('safe', true);
return $node;
}
} else {
$type = Template::ARRAY_CALL;
// slice?
$slice = false;
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
$slice = true;
$arg = new ConstantExpression(0, $token->getLine());
} else {
$arg = $this->parseExpression();
}
if ($stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
$slice = true;
}
if ($slice) {
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) {
$length = new ConstantExpression(null, $token->getLine());
} else {
$length = $this->parseExpression();
}
$class = $this->getFilterNodeClass('slice', $token->getLine());
$arguments = new Node([$arg, $length]);
$filter = new $class($node, new ConstantExpression('slice', $token->getLine()), $arguments, $token->getLine());
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']');
return $filter;
}
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']');
}
return new GetAttrExpression($node, $arg, $arguments, $type, $lineno);
}
public function parseFilterExpression($node)
{
$this->parser->getStream()->next();
return $this->parseFilterExpressionRaw($node);
}
public function parseFilterExpressionRaw($node, $tag = null)
{
while (true) {
$token = $this->parser->getStream()->expect(/* Token::NAME_TYPE */ 5);
$name = new ConstantExpression($token->getValue(), $token->getLine());
if (!$this->parser->getStream()->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
$arguments = new Node();
} else {
$arguments = $this->parseArguments(true, false, true);
}
$class = $this->getFilterNodeClass($name->getAttribute('value'), $token->getLine());
$node = new $class($node, $name, $arguments, $token->getLine(), $tag);
if (!$this->parser->getStream()->test(/* Token::PUNCTUATION_TYPE */ 9, '|')) {
break;
}
$this->parser->getStream()->next();
}
return $node;
}
/**
* Parses arguments.
*
* @param bool $namedArguments Whether to allow named arguments or not
* @param bool $definition Whether we are parsing arguments for a function definition
*
* @return Node
*
* @throws SyntaxError
*/
public function parseArguments($namedArguments = false, $definition = false, $allowArrow = false)
{
$args = [];
$stream = $this->parser->getStream();
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '(', 'A list of arguments must begin with an opening parenthesis');
while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, ')')) {
if (!empty($args)) {
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'Arguments must be separated by a comma');
// if the comma above was a trailing comma, early exit the argument parse loop
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ')')) {
break;
}
}
if ($definition) {
$token = $stream->expect(/* Token::NAME_TYPE */ 5, null, 'An argument must be a name');
$value = new NameExpression($token->getValue(), $this->parser->getCurrentToken()->getLine());
} else {
$value = $this->parseExpression(0, $allowArrow);
}
$name = null;
if ($namedArguments && $token = $stream->nextIf(/* Token::OPERATOR_TYPE */ 8, '=')) {
if (!$value instanceof NameExpression) {
throw new SyntaxError(sprintf('A parameter name must be a string, "%s" given.', \get_class($value)), $token->getLine(), $stream->getSourceContext());
}
$name = $value->getAttribute('name');
if ($definition) {
$value = $this->parsePrimaryExpression();
if (!$this->checkConstantExpression($value)) {
throw new SyntaxError('A default value for an argument must be a constant (a boolean, a string, a number, or an array).', $token->getLine(), $stream->getSourceContext());
}
} else {
$value = $this->parseExpression(0, $allowArrow);
}
}
if ($definition) {
if (null === $name) {
$name = $value->getAttribute('name');
$value = new ConstantExpression(null, $this->parser->getCurrentToken()->getLine());
}
$args[$name] = $value;
} else {
if (null === $name) {
$args[] = $value;
} else {
$args[$name] = $value;
}
}
}
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ')', 'A list of arguments must be closed by a parenthesis');
return new Node($args);
}
public function parseAssignmentExpression()
{
$stream = $this->parser->getStream();
$targets = [];
while (true) {
$token = $this->parser->getCurrentToken();
if ($stream->test(/* Token::OPERATOR_TYPE */ 8) && preg_match(Lexer::REGEX_NAME, $token->getValue())) {
// in this context, string operators are variable names
$this->parser->getStream()->next();
} else {
$stream->expect(/* Token::NAME_TYPE */ 5, null, 'Only variables can be assigned to');
}
$value = $token->getValue();
if (\in_array(strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ['true', 'false', 'none', 'null'])) {
throw new SyntaxError(sprintf('You cannot assign a value to "%s".', $value), $token->getLine(), $stream->getSourceContext());
}
$targets[] = new AssignNameExpression($value, $token->getLine());
if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
break;
}
}
return new Node($targets);
}
public function parseMultitargetExpression()
{
$targets = [];
while (true) {
$targets[] = $this->parseExpression();
if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
break;
}
}
return new Node($targets);
}
private function parseNotTestExpression(Node $node): NotUnary
{
return new NotUnary($this->parseTestExpression($node), $this->parser->getCurrentToken()->getLine());
}
private function parseTestExpression(Node $node): TestExpression
{
$stream = $this->parser->getStream();
list($name, $test) = $this->getTest($node->getTemplateLine());
$class = $this->getTestNodeClass($test);
$arguments = null;
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
$arguments = $this->parseArguments(true);
} elseif ($test->hasOneMandatoryArgument()) {
$arguments = new Node([0 => $this->parsePrimaryExpression()]);
}
if ('defined' === $name && $node instanceof NameExpression && null !== $alias = $this->parser->getImportedSymbol('function', $node->getAttribute('name'))) {
$node = new MethodCallExpression($alias['node'], $alias['name'], new ArrayExpression([], $node->getTemplateLine()), $node->getTemplateLine());
$node->setAttribute('safe', true);
}
return new $class($node, $name, $arguments, $this->parser->getCurrentToken()->getLine());
}
private function getTest(int $line): array
{
$stream = $this->parser->getStream();
$name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
if ($test = $this->env->getTest($name)) {
return [$name, $test];
}
if ($stream->test(/* Token::NAME_TYPE */ 5)) {
// try 2-words tests
$name = $name.' '.$this->parser->getCurrentToken()->getValue();
if ($test = $this->env->getTest($name)) {
$stream->next();
return [$name, $test];
}
}
$e = new SyntaxError(sprintf('Unknown "%s" test.', $name), $line, $stream->getSourceContext());
$e->addSuggestions($name, array_keys($this->env->getTests()));
throw $e;
}
private function getTestNodeClass(TwigTest $test): string
{
if ($test->isDeprecated()) {
$stream = $this->parser->getStream();
$message = sprintf('Twig Test "%s" is deprecated', $test->getName());
if ($test->getDeprecatedVersion()) {
$message .= sprintf(' since version %s', $test->getDeprecatedVersion());
}
if ($test->getAlternative()) {
$message .= sprintf('. Use "%s" instead', $test->getAlternative());
}
$src = $stream->getSourceContext();
$message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $stream->getCurrent()->getLine());
@trigger_error($message, \E_USER_DEPRECATED);
}
return $test->getNodeClass();
}
private function getFunctionNodeClass(string $name, int $line): string
{
if (!$function = $this->env->getFunction($name)) {
$e = new SyntaxError(sprintf('Unknown "%s" function.', $name), $line, $this->parser->getStream()->getSourceContext());
$e->addSuggestions($name, array_keys($this->env->getFunctions()));
throw $e;
}
if ($function->isDeprecated()) {
$message = sprintf('Twig Function "%s" is deprecated', $function->getName());
if ($function->getDeprecatedVersion()) {
$message .= sprintf(' since version %s', $function->getDeprecatedVersion());
}
if ($function->getAlternative()) {
$message .= sprintf('. Use "%s" instead', $function->getAlternative());
}
$src = $this->parser->getStream()->getSourceContext();
$message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $line);
@trigger_error($message, \E_USER_DEPRECATED);
}
return $function->getNodeClass();
}
private function getFilterNodeClass(string $name, int $line): string
{
if (!$filter = $this->env->getFilter($name)) {
$e = new SyntaxError(sprintf('Unknown "%s" filter.', $name), $line, $this->parser->getStream()->getSourceContext());
$e->addSuggestions($name, array_keys($this->env->getFilters()));
throw $e;
}
if ($filter->isDeprecated()) {
$message = sprintf('Twig Filter "%s" is deprecated', $filter->getName());
if ($filter->getDeprecatedVersion()) {
$message .= sprintf(' since version %s', $filter->getDeprecatedVersion());
}
if ($filter->getAlternative()) {
$message .= sprintf('. Use "%s" instead', $filter->getAlternative());
}
$src = $this->parser->getStream()->getSourceContext();
$message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $line);
@trigger_error($message, \E_USER_DEPRECATED);
}
return $filter->getNodeClass();
}
// checks that the node only contains "constant" elements
private function checkConstantExpression(Node $node): bool
{
if (!($node instanceof ConstantExpression || $node instanceof ArrayExpression
|| $node instanceof NegUnary || $node instanceof PosUnary
)) {
return false;
}
foreach ($node as $n) {
if (!$this->checkConstantExpression($n)) {
return false;
}
}
return true;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\SyntaxError;
/**
* Represents a token stream.
*
* @author Fabien Potencier <[email protected]>
*/
final class TokenStream
{
private $tokens;
private $current = 0;
private $source;
public function __construct(array $tokens, Source $source = null)
{
$this->tokens = $tokens;
$this->source = $source ?: new Source('', '');
}
public function __toString()
{
return implode("\n", $this->tokens);
}
public function injectTokens(array $tokens)
{
$this->tokens = array_merge(\array_slice($this->tokens, 0, $this->current), $tokens, \array_slice($this->tokens, $this->current));
}
/**
* Sets the pointer to the next token and returns the old one.
*/
public function next(): Token
{
if (!isset($this->tokens[++$this->current])) {
throw new SyntaxError('Unexpected end of template.', $this->tokens[$this->current - 1]->getLine(), $this->source);
}
return $this->tokens[$this->current - 1];
}
/**
* Tests a token, sets the pointer to the next one and returns it or throws a syntax error.
*
* @return Token|null The next token if the condition is true, null otherwise
*/
public function nextIf($primary, $secondary = null)
{
if ($this->tokens[$this->current]->test($primary, $secondary)) {
return $this->next();
}
}
/**
* Tests a token and returns it or throws a syntax error.
*/
public function expect($type, $value = null, string $message = null): Token
{
$token = $this->tokens[$this->current];
if (!$token->test($type, $value)) {
$line = $token->getLine();
throw new SyntaxError(sprintf('%sUnexpected token "%s"%s ("%s" expected%s).',
$message ? $message.'. ' : '',
Token::typeToEnglish($token->getType()),
$token->getValue() ? sprintf(' of value "%s"', $token->getValue()) : '',
Token::typeToEnglish($type), $value ? sprintf(' with value "%s"', $value) : ''),
$line,
$this->source
);
}
$this->next();
return $token;
}
/**
* Looks at the next token.
*/
public function look(int $number = 1): Token
{
if (!isset($this->tokens[$this->current + $number])) {
throw new SyntaxError('Unexpected end of template.', $this->tokens[$this->current + $number - 1]->getLine(), $this->source);
}
return $this->tokens[$this->current + $number];
}
/**
* Tests the current token.
*/
public function test($primary, $secondary = null): bool
{
return $this->tokens[$this->current]->test($primary, $secondary);
}
/**
* Checks if end of stream was reached.
*/
public function isEOF(): bool
{
return /* Token::EOF_TYPE */ -1 === $this->tokens[$this->current]->getType();
}
public function getCurrent(): Token
{
return $this->tokens[$this->current];
}
/**
* Gets the source associated with this stream.
*
* @internal
*/
public function getSourceContext(): Source
{
return $this->source;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Node;
/**
* Represents a template filter.
*
* @author Fabien Potencier <[email protected]>
*
* @see https://twig.symfony.com/doc/templates.html#filters
*/
final class TwigFilter
{
private $name;
private $callable;
private $options;
private $arguments = [];
/**
* @param callable|null $callable A callable implementing the filter. If null, you need to overwrite the "node_class" option to customize compilation.
*/
public function __construct(string $name, $callable = null, array $options = [])
{
$this->name = $name;
$this->callable = $callable;
$this->options = array_merge([
'needs_environment' => false,
'needs_context' => false,
'is_variadic' => false,
'is_safe' => null,
'is_safe_callback' => null,
'pre_escape' => null,
'preserves_safety' => null,
'node_class' => FilterExpression::class,
'deprecated' => false,
'alternative' => null,
], $options);
}
public function getName(): string
{
return $this->name;
}
/**
* Returns the callable to execute for this filter.
*
* @return callable|null
*/
public function getCallable()
{
return $this->callable;
}
public function getNodeClass(): string
{
return $this->options['node_class'];
}
public function setArguments(array $arguments): void
{
$this->arguments = $arguments;
}
public function getArguments(): array
{
return $this->arguments;
}
public function needsEnvironment(): bool
{
return $this->options['needs_environment'];
}
public function needsContext(): bool
{
return $this->options['needs_context'];
}
public function getSafe(Node $filterArgs): ?array
{
if (null !== $this->options['is_safe']) {
return $this->options['is_safe'];
}
if (null !== $this->options['is_safe_callback']) {
return $this->options['is_safe_callback']($filterArgs);
}
return null;
}
public function getPreservesSafety(): ?array
{
return $this->options['preserves_safety'];
}
public function getPreEscape(): ?string
{
return $this->options['pre_escape'];
}
public function isVariadic(): bool
{
return $this->options['is_variadic'];
}
public function isDeprecated(): bool
{
return (bool) $this->options['deprecated'];
}
public function getDeprecatedVersion(): string
{
return \is_bool($this->options['deprecated']) ? '' : $this->options['deprecated'];
}
public function getAlternative(): ?string
{
return $this->options['alternative'];
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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;
use Twig\Cache\CacheInterface;
use Twig\Cache\FilesystemCache;
use Twig\Cache\NullCache;
use Twig\Error\Error;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Extension\CoreExtension;
use Twig\Extension\EscaperExtension;
use Twig\Extension\ExtensionInterface;
use Twig\Extension\OptimizerExtension;
use Twig\Loader\ArrayLoader;
use Twig\Loader\ChainLoader;
use Twig\Loader\LoaderInterface;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\NodeVisitor\NodeVisitorInterface;
use Twig\RuntimeLoader\RuntimeLoaderInterface;
use Twig\TokenParser\TokenParserInterface;
/**
* Stores the Twig configuration and renders templates.
*
* @author Fabien Potencier <[email protected]>
*/
class Environment
{
public const VERSION = '3.4.3';
public const VERSION_ID = 30403;
public const MAJOR_VERSION = 3;
public const MINOR_VERSION = 4;
public const RELEASE_VERSION = 3;
public const EXTRA_VERSION = '';
private $charset;
private $loader;
private $debug;
private $autoReload;
private $cache;
private $lexer;
private $parser;
private $compiler;
private $globals = [];
private $resolvedGlobals;
private $loadedTemplates;
private $strictVariables;
private $templateClassPrefix = '__TwigTemplate_';
private $originalCache;
private $extensionSet;
private $runtimeLoaders = [];
private $runtimes = [];
private $optionsHash;
/**
* Constructor.
*
* Available options:
*
* * debug: When set to true, it automatically set "auto_reload" to true as
* well (default to false).
*
* * charset: The charset used by the templates (default to UTF-8).
*
* * cache: An absolute path where to store the compiled templates,
* a \Twig\Cache\CacheInterface implementation,
* or false to disable compilation cache (default).
*
* * auto_reload: Whether to reload the template if the original source changed.
* If you don't provide the auto_reload option, it will be
* determined automatically based on the debug value.
*
* * strict_variables: Whether to ignore invalid variables in templates
* (default to false).
*
* * autoescape: Whether to enable auto-escaping (default to html):
* * false: disable auto-escaping
* * html, js: set the autoescaping to one of the supported strategies
* * name: set the autoescaping strategy based on the template name extension
* * PHP callback: a PHP callback that returns an escaping strategy based on the template "name"
*
* * optimizations: A flag that indicates which optimizations to apply
* (default to -1 which means that all optimizations are enabled;
* set it to 0 to disable).
*/
public function __construct(LoaderInterface $loader, $options = [])
{
$this->setLoader($loader);
$options = array_merge([
'debug' => false,
'charset' => 'UTF-8',
'strict_variables' => false,
'autoescape' => 'html',
'cache' => false,
'auto_reload' => null,
'optimizations' => -1,
], $options);
$this->debug = (bool) $options['debug'];
$this->setCharset($options['charset'] ?? 'UTF-8');
$this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload'];
$this->strictVariables = (bool) $options['strict_variables'];
$this->setCache($options['cache']);
$this->extensionSet = new ExtensionSet();
$this->addExtension(new CoreExtension());
$this->addExtension(new EscaperExtension($options['autoescape']));
$this->addExtension(new OptimizerExtension($options['optimizations']));
}
/**
* Enables debugging mode.
*/
public function enableDebug()
{
$this->debug = true;
$this->updateOptionsHash();
}
/**
* Disables debugging mode.
*/
public function disableDebug()
{
$this->debug = false;
$this->updateOptionsHash();
}
/**
* Checks if debug mode is enabled.
*
* @return bool true if debug mode is enabled, false otherwise
*/
public function isDebug()
{
return $this->debug;
}
/**
* Enables the auto_reload option.
*/
public function enableAutoReload()
{
$this->autoReload = true;
}
/**
* Disables the auto_reload option.
*/
public function disableAutoReload()
{
$this->autoReload = false;
}
/**
* Checks if the auto_reload option is enabled.
*
* @return bool true if auto_reload is enabled, false otherwise
*/
public function isAutoReload()
{
return $this->autoReload;
}
/**
* Enables the strict_variables option.
*/
public function enableStrictVariables()
{
$this->strictVariables = true;
$this->updateOptionsHash();
}
/**
* Disables the strict_variables option.
*/
public function disableStrictVariables()
{
$this->strictVariables = false;
$this->updateOptionsHash();
}
/**
* Checks if the strict_variables option is enabled.
*
* @return bool true if strict_variables is enabled, false otherwise
*/
public function isStrictVariables()
{
return $this->strictVariables;
}
/**
* Gets the current cache implementation.
*
* @param bool $original Whether to return the original cache option or the real cache instance
*
* @return CacheInterface|string|false A Twig\Cache\CacheInterface implementation,
* an absolute path to the compiled templates,
* or false to disable cache
*/
public function getCache($original = true)
{
return $original ? $this->originalCache : $this->cache;
}
/**
* Sets the current cache implementation.
*
* @param CacheInterface|string|false $cache A Twig\Cache\CacheInterface implementation,
* an absolute path to the compiled templates,
* or false to disable cache
*/
public function setCache($cache)
{
if (\is_string($cache)) {
$this->originalCache = $cache;
$this->cache = new FilesystemCache($cache, $this->autoReload ? FilesystemCache::FORCE_BYTECODE_INVALIDATION : 0);
} elseif (false === $cache) {
$this->originalCache = $cache;
$this->cache = new NullCache();
} elseif ($cache instanceof CacheInterface) {
$this->originalCache = $this->cache = $cache;
} else {
throw new \LogicException('Cache can only be a string, false, or a \Twig\Cache\CacheInterface implementation.');
}
}
/**
* Gets the template class associated with the given string.
*
* The generated template class is based on the following parameters:
*
* * The cache key for the given template;
* * The currently enabled extensions;
* * Whether the Twig C extension is available or not;
* * PHP version;
* * Twig version;
* * Options with what environment was created.
*
* @param string $name The name for which to calculate the template class name
* @param int|null $index The index if it is an embedded template
*
* @internal
*/
public function getTemplateClass(string $name, int $index = null): string
{
$key = $this->getLoader()->getCacheKey($name).$this->optionsHash;
return $this->templateClassPrefix.hash(\PHP_VERSION_ID < 80100 ? 'sha256' : 'xxh128', $key).(null === $index ? '' : '___'.$index);
}
/**
* Renders a template.
*
* @param string|TemplateWrapper $name The template name
*
* @throws LoaderError When the template cannot be found
* @throws SyntaxError When an error occurred during compilation
* @throws RuntimeError When an error occurred during rendering
*/
public function render($name, array $context = []): string
{
return $this->load($name)->render($context);
}
/**
* Displays a template.
*
* @param string|TemplateWrapper $name The template name
*
* @throws LoaderError When the template cannot be found
* @throws SyntaxError When an error occurred during compilation
* @throws RuntimeError When an error occurred during rendering
*/
public function display($name, array $context = []): void
{
$this->load($name)->display($context);
}
/**
* Loads a template.
*
* @param string|TemplateWrapper $name The template name
*
* @throws LoaderError When the template cannot be found
* @throws RuntimeError When a previously generated cache is corrupted
* @throws SyntaxError When an error occurred during compilation
*/
public function load($name): TemplateWrapper
{
if ($name instanceof TemplateWrapper) {
return $name;
}
return new TemplateWrapper($this, $this->loadTemplate($this->getTemplateClass($name), $name));
}
/**
* Loads a template internal representation.
*
* This method is for internal use only and should never be called
* directly.
*
* @param string $name The template name
* @param int $index The index if it is an embedded template
*
* @throws LoaderError When the template cannot be found
* @throws RuntimeError When a previously generated cache is corrupted
* @throws SyntaxError When an error occurred during compilation
*
* @internal
*/
public function loadTemplate(string $cls, string $name, int $index = null): Template
{
$mainCls = $cls;
if (null !== $index) {
$cls .= '___'.$index;
}
if (isset($this->loadedTemplates[$cls])) {
return $this->loadedTemplates[$cls];
}
if (!class_exists($cls, false)) {
$key = $this->cache->generateKey($name, $mainCls);
if (!$this->isAutoReload() || $this->isTemplateFresh($name, $this->cache->getTimestamp($key))) {
$this->cache->load($key);
}
$source = null;
if (!class_exists($cls, false)) {
$source = $this->getLoader()->getSourceContext($name);
$content = $this->compileSource($source);
$this->cache->write($key, $content);
$this->cache->load($key);
if (!class_exists($mainCls, false)) {
/* Last line of defense if either $this->bcWriteCacheFile was used,
* $this->cache is implemented as a no-op or we have a race condition
* where the cache was cleared between the above calls to write to and load from
* the cache.
*/
eval('?>'.$content);
}
if (!class_exists($cls, false)) {
throw new RuntimeError(sprintf('Failed to load Twig template "%s", index "%s": cache might be corrupted.', $name, $index), -1, $source);
}
}
}
$this->extensionSet->initRuntime();
return $this->loadedTemplates[$cls] = new $cls($this);
}
/**
* Creates a template from source.
*
* This method should not be used as a generic way to load templates.
*
* @param string $template The template source
* @param string $name An optional name of the template to be used in error messages
*
* @throws LoaderError When the template cannot be found
* @throws SyntaxError When an error occurred during compilation
*/
public function createTemplate(string $template, string $name = null): TemplateWrapper
{
$hash = hash(\PHP_VERSION_ID < 80100 ? 'sha256' : 'xxh128', $template, false);
if (null !== $name) {
$name = sprintf('%s (string template %s)', $name, $hash);
} else {
$name = sprintf('__string_template__%s', $hash);
}
$loader = new ChainLoader([
new ArrayLoader([$name => $template]),
$current = $this->getLoader(),
]);
$this->setLoader($loader);
try {
return new TemplateWrapper($this, $this->loadTemplate($this->getTemplateClass($name), $name));
} finally {
$this->setLoader($current);
}
}
/**
* Returns true if the template is still fresh.
*
* Besides checking the loader for freshness information,
* this method also checks if the enabled extensions have
* not changed.
*
* @param int $time The last modification time of the cached template
*/
public function isTemplateFresh(string $name, int $time): bool
{
return $this->extensionSet->getLastModified() <= $time && $this->getLoader()->isFresh($name, $time);
}
/**
* Tries to load a template consecutively from an array.
*
* Similar to load() but it also accepts instances of \Twig\Template and
* \Twig\TemplateWrapper, and an array of templates where each is tried to be loaded.
*
* @param string|TemplateWrapper|array $names A template or an array of templates to try consecutively
*
* @throws LoaderError When none of the templates can be found
* @throws SyntaxError When an error occurred during compilation
*/
public function resolveTemplate($names): TemplateWrapper
{
if (!\is_array($names)) {
return $this->load($names);
}
$count = \count($names);
foreach ($names as $name) {
if ($name instanceof Template) {
return $name;
}
if ($name instanceof TemplateWrapper) {
return $name;
}
if (1 !== $count && !$this->getLoader()->exists($name)) {
continue;
}
return $this->load($name);
}
throw new LoaderError(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names)));
}
public function setLexer(Lexer $lexer)
{
$this->lexer = $lexer;
}
/**
* @throws SyntaxError When the code is syntactically wrong
*/
public function tokenize(Source $source): TokenStream
{
if (null === $this->lexer) {
$this->lexer = new Lexer($this);
}
return $this->lexer->tokenize($source);
}
public function setParser(Parser $parser)
{
$this->parser = $parser;
}
/**
* Converts a token stream to a node tree.
*
* @throws SyntaxError When the token stream is syntactically or semantically wrong
*/
public function parse(TokenStream $stream): ModuleNode
{
if (null === $this->parser) {
$this->parser = new Parser($this);
}
return $this->parser->parse($stream);
}
public function setCompiler(Compiler $compiler)
{
$this->compiler = $compiler;
}
/**
* Compiles a node and returns the PHP code.
*/
public function compile(Node $node): string
{
if (null === $this->compiler) {
$this->compiler = new Compiler($this);
}
return $this->compiler->compile($node)->getSource();
}
/**
* Compiles a template source code.
*
* @throws SyntaxError When there was an error during tokenizing, parsing or compiling
*/
public function compileSource(Source $source): string
{
try {
return $this->compile($this->parse($this->tokenize($source)));
} catch (Error $e) {
$e->setSourceContext($source);
throw $e;
} catch (\Exception $e) {
throw new SyntaxError(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e);
}
}
public function setLoader(LoaderInterface $loader)
{
$this->loader = $loader;
}
public function getLoader(): LoaderInterface
{
return $this->loader;
}
public function setCharset(string $charset)
{
if ('UTF8' === $charset = null === $charset ? null : strtoupper($charset)) {
// iconv on Windows requires "UTF-8" instead of "UTF8"
$charset = 'UTF-8';
}
$this->charset = $charset;
}
public function getCharset(): string
{
return $this->charset;
}
public function hasExtension(string $class): bool
{
return $this->extensionSet->hasExtension($class);
}
public function addRuntimeLoader(RuntimeLoaderInterface $loader)
{
$this->runtimeLoaders[] = $loader;
}
/**
* @template TExtension of ExtensionInterface
*
* @param class-string<TExtension> $class
*
* @return TExtension
*/
public function getExtension(string $class): ExtensionInterface
{
return $this->extensionSet->getExtension($class);
}
/**
* Returns the runtime implementation of a Twig element (filter/function/tag/test).
*
* @template TRuntime of object
*
* @param class-string<TRuntime> $class A runtime class name
*
* @return TRuntime The runtime implementation
*
* @throws RuntimeError When the template cannot be found
*/
public function getRuntime(string $class)
{
if (isset($this->runtimes[$class])) {
return $this->runtimes[$class];
}
foreach ($this->runtimeLoaders as $loader) {
if (null !== $runtime = $loader->load($class)) {
return $this->runtimes[$class] = $runtime;
}
}
throw new RuntimeError(sprintf('Unable to load the "%s" runtime.', $class));
}
public function addExtension(ExtensionInterface $extension)
{
$this->extensionSet->addExtension($extension);
$this->updateOptionsHash();
}
/**
* @param ExtensionInterface[] $extensions An array of extensions
*/
public function setExtensions(array $extensions)
{
$this->extensionSet->setExtensions($extensions);
$this->updateOptionsHash();
}
/**
* @return ExtensionInterface[] An array of extensions (keys are for internal usage only and should not be relied on)
*/
public function getExtensions(): array
{
return $this->extensionSet->getExtensions();
}
public function addTokenParser(TokenParserInterface $parser)
{
$this->extensionSet->addTokenParser($parser);
}
/**
* @return TokenParserInterface[]
*
* @internal
*/
public function getTokenParsers(): array
{
return $this->extensionSet->getTokenParsers();
}
/**
* @internal
*/
public function getTokenParser(string $name): ?TokenParserInterface
{
return $this->extensionSet->getTokenParser($name);
}
public function registerUndefinedTokenParserCallback(callable $callable): void
{
$this->extensionSet->registerUndefinedTokenParserCallback($callable);
}
public function addNodeVisitor(NodeVisitorInterface $visitor)
{
$this->extensionSet->addNodeVisitor($visitor);
}
/**
* @return NodeVisitorInterface[]
*
* @internal
*/
public function getNodeVisitors(): array
{
return $this->extensionSet->getNodeVisitors();
}
public function addFilter(TwigFilter $filter)
{
$this->extensionSet->addFilter($filter);
}
/**
* @internal
*/
public function getFilter(string $name): ?TwigFilter
{
return $this->extensionSet->getFilter($name);
}
public function registerUndefinedFilterCallback(callable $callable): void
{
$this->extensionSet->registerUndefinedFilterCallback($callable);
}
/**
* Gets the registered Filters.
*
* Be warned that this method cannot return filters defined with registerUndefinedFilterCallback.
*
* @return TwigFilter[]
*
* @see registerUndefinedFilterCallback
*
* @internal
*/
public function getFilters(): array
{
return $this->extensionSet->getFilters();
}
public function addTest(TwigTest $test)
{
$this->extensionSet->addTest($test);
}
/**
* @return TwigTest[]
*
* @internal
*/
public function getTests(): array
{
return $this->extensionSet->getTests();
}
/**
* @internal
*/
public function getTest(string $name): ?TwigTest
{
return $this->extensionSet->getTest($name);
}
public function addFunction(TwigFunction $function)
{
$this->extensionSet->addFunction($function);
}
/**
* @internal
*/
public function getFunction(string $name): ?TwigFunction
{
return $this->extensionSet->getFunction($name);
}
public function registerUndefinedFunctionCallback(callable $callable): void
{
$this->extensionSet->registerUndefinedFunctionCallback($callable);
}
/**
* Gets registered functions.
*
* Be warned that this method cannot return functions defined with registerUndefinedFunctionCallback.
*
* @return TwigFunction[]
*
* @see registerUndefinedFunctionCallback
*
* @internal
*/
public function getFunctions(): array
{
return $this->extensionSet->getFunctions();
}
/**
* Registers a Global.
*
* New globals can be added before compiling or rendering a template;
* but after, you can only update existing globals.
*
* @param mixed $value The global value
*/
public function addGlobal(string $name, $value)
{
if ($this->extensionSet->isInitialized() && !\array_key_exists($name, $this->getGlobals())) {
throw new \LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name));
}
if (null !== $this->resolvedGlobals) {
$this->resolvedGlobals[$name] = $value;
} else {
$this->globals[$name] = $value;
}
}
/**
* @internal
*/
public function getGlobals(): array
{
if ($this->extensionSet->isInitialized()) {
if (null === $this->resolvedGlobals) {
$this->resolvedGlobals = array_merge($this->extensionSet->getGlobals(), $this->globals);
}
return $this->resolvedGlobals;
}
return array_merge($this->extensionSet->getGlobals(), $this->globals);
}
public function mergeGlobals(array $context): array
{
// we don't use array_merge as the context being generally
// bigger than globals, this code is faster.
foreach ($this->getGlobals() as $key => $value) {
if (!\array_key_exists($key, $context)) {
$context[$key] = $value;
}
}
return $context;
}
/**
* @internal
*/
public function getUnaryOperators(): array
{
return $this->extensionSet->getUnaryOperators();
}
/**
* @internal
*/
public function getBinaryOperators(): array
{
return $this->extensionSet->getBinaryOperators();
}
private function updateOptionsHash(): void
{
$this->optionsHash = implode(':', [
$this->extensionSet->getSignature(),
\PHP_MAJOR_VERSION,
\PHP_MINOR_VERSION,
self::VERSION,
(int) $this->debug,
(int) $this->strictVariables,
]);
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
/**
* @author Fabien Potencier <[email protected]>
*/
final class Token
{
private $value;
private $type;
private $lineno;
public const EOF_TYPE = -1;
public const TEXT_TYPE = 0;
public const BLOCK_START_TYPE = 1;
public const VAR_START_TYPE = 2;
public const BLOCK_END_TYPE = 3;
public const VAR_END_TYPE = 4;
public const NAME_TYPE = 5;
public const NUMBER_TYPE = 6;
public const STRING_TYPE = 7;
public const OPERATOR_TYPE = 8;
public const PUNCTUATION_TYPE = 9;
public const INTERPOLATION_START_TYPE = 10;
public const INTERPOLATION_END_TYPE = 11;
public const ARROW_TYPE = 12;
public function __construct(int $type, $value, int $lineno)
{
$this->type = $type;
$this->value = $value;
$this->lineno = $lineno;
}
public function __toString()
{
return sprintf('%s(%s)', self::typeToString($this->type, true), $this->value);
}
/**
* Tests the current token for a type and/or a value.
*
* Parameters may be:
* * just type
* * type and value (or array of possible values)
* * just value (or array of possible values) (NAME_TYPE is used as type)
*
* @param array|string|int $type The type to test
* @param array|string|null $values The token value
*/
public function test($type, $values = null): bool
{
if (null === $values && !\is_int($type)) {
$values = $type;
$type = self::NAME_TYPE;
}
return ($this->type === $type) && (
null === $values ||
(\is_array($values) && \in_array($this->value, $values)) ||
$this->value == $values
);
}
public function getLine(): int
{
return $this->lineno;
}
public function getType(): int
{
return $this->type;
}
public function getValue()
{
return $this->value;
}
public static function typeToString(int $type, bool $short = false): string
{
switch ($type) {
case self::EOF_TYPE:
$name = 'EOF_TYPE';
break;
case self::TEXT_TYPE:
$name = 'TEXT_TYPE';
break;
case self::BLOCK_START_TYPE:
$name = 'BLOCK_START_TYPE';
break;
case self::VAR_START_TYPE:
$name = 'VAR_START_TYPE';
break;
case self::BLOCK_END_TYPE:
$name = 'BLOCK_END_TYPE';
break;
case self::VAR_END_TYPE:
$name = 'VAR_END_TYPE';
break;
case self::NAME_TYPE:
$name = 'NAME_TYPE';
break;
case self::NUMBER_TYPE:
$name = 'NUMBER_TYPE';
break;
case self::STRING_TYPE:
$name = 'STRING_TYPE';
break;
case self::OPERATOR_TYPE:
$name = 'OPERATOR_TYPE';
break;
case self::PUNCTUATION_TYPE:
$name = 'PUNCTUATION_TYPE';
break;
case self::INTERPOLATION_START_TYPE:
$name = 'INTERPOLATION_START_TYPE';
break;
case self::INTERPOLATION_END_TYPE:
$name = 'INTERPOLATION_END_TYPE';
break;
case self::ARROW_TYPE:
$name = 'ARROW_TYPE';
break;
default:
throw new \LogicException(sprintf('Token of type "%s" does not exist.', $type));
}
return $short ? $name : 'Twig\Token::'.$name;
}
public static function typeToEnglish(int $type): string
{
switch ($type) {
case self::EOF_TYPE:
return 'end of template';
case self::TEXT_TYPE:
return 'text';
case self::BLOCK_START_TYPE:
return 'begin of statement block';
case self::VAR_START_TYPE:
return 'begin of print statement';
case self::BLOCK_END_TYPE:
return 'end of statement block';
case self::VAR_END_TYPE:
return 'end of print statement';
case self::NAME_TYPE:
return 'name';
case self::NUMBER_TYPE:
return 'number';
case self::STRING_TYPE:
return 'string';
case self::OPERATOR_TYPE:
return 'operator';
case self::PUNCTUATION_TYPE:
return 'punctuation';
case self::INTERPOLATION_START_TYPE:
return 'begin of string interpolation';
case self::INTERPOLATION_END_TYPE:
return 'end of string interpolation';
case self::ARROW_TYPE:
return 'arrow function';
default:
throw new \LogicException(sprintf('Token of type "%s" does not exist.', $type));
}
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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;
use Twig\Node\Expression\TestExpression;
/**
* Represents a template test.
*
* @author Fabien Potencier <[email protected]>
*
* @see https://twig.symfony.com/doc/templates.html#test-operator
*/
final class TwigTest
{
private $name;
private $callable;
private $options;
private $arguments = [];
/**
* @param callable|null $callable A callable implementing the test. If null, you need to overwrite the "node_class" option to customize compilation.
*/
public function __construct(string $name, $callable = null, array $options = [])
{
$this->name = $name;
$this->callable = $callable;
$this->options = array_merge([
'is_variadic' => false,
'node_class' => TestExpression::class,
'deprecated' => false,
'alternative' => null,
'one_mandatory_argument' => false,
], $options);
}
public function getName(): string
{
return $this->name;
}
/**
* Returns the callable to execute for this test.
*
* @return callable|null
*/
public function getCallable()
{
return $this->callable;
}
public function getNodeClass(): string
{
return $this->options['node_class'];
}
public function setArguments(array $arguments): void
{
$this->arguments = $arguments;
}
public function getArguments(): array
{
return $this->arguments;
}
public function isVariadic(): bool
{
return (bool) $this->options['is_variadic'];
}
public function isDeprecated(): bool
{
return (bool) $this->options['deprecated'];
}
public function getDeprecatedVersion(): string
{
return \is_bool($this->options['deprecated']) ? '' : $this->options['deprecated'];
}
public function getAlternative(): ?string
{
return $this->options['alternative'];
}
public function hasOneMandatoryArgument(): bool
{
return (bool) $this->options['one_mandatory_argument'];
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\SyntaxError;
/**
* @author Fabien Potencier <[email protected]>
*/
class Lexer
{
private $tokens;
private $code;
private $cursor;
private $lineno;
private $end;
private $state;
private $states;
private $brackets;
private $env;
private $source;
private $options;
private $regexes;
private $position;
private $positions;
private $currentVarBlockLine;
public const STATE_DATA = 0;
public const STATE_BLOCK = 1;
public const STATE_VAR = 2;
public const STATE_STRING = 3;
public const STATE_INTERPOLATION = 4;
public const REGEX_NAME = '/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A';
public const REGEX_NUMBER = '/[0-9]+(?:\.[0-9]+)?([Ee][\+\-][0-9]+)?/A';
public const REGEX_STRING = '/"([^#"\\\\]*(?:\\\\.[^#"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'/As';
public const REGEX_DQ_STRING_DELIM = '/"/A';
public const REGEX_DQ_STRING_PART = '/[^#"\\\\]*(?:(?:\\\\.|#(?!\{))[^#"\\\\]*)*/As';
public const PUNCTUATION = '()[]{}?:.,|';
public function __construct(Environment $env, array $options = [])
{
$this->env = $env;
$this->options = array_merge([
'tag_comment' => ['{#', '#}'],
'tag_block' => ['{%', '%}'],
'tag_variable' => ['{{', '}}'],
'whitespace_trim' => '-',
'whitespace_line_trim' => '~',
'whitespace_line_chars' => ' \t\0\x0B',
'interpolation' => ['#{', '}'],
], $options);
// when PHP 7.3 is the min version, we will be able to remove the '#' part in preg_quote as it's part of the default
$this->regexes = [
// }}
'lex_var' => '{
\s*
(?:'.
preg_quote($this->options['whitespace_trim'].$this->options['tag_variable'][1], '#').'\s*'. // -}}\s*
'|'.
preg_quote($this->options['whitespace_line_trim'].$this->options['tag_variable'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~}}[ \t\0\x0B]*
'|'.
preg_quote($this->options['tag_variable'][1], '#'). // }}
')
}Ax',
// %}
'lex_block' => '{
\s*
(?:'.
preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*\n?'. // -%}\s*\n?
'|'.
preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]*
'|'.
preg_quote($this->options['tag_block'][1], '#').'\n?'. // %}\n?
')
}Ax',
// {% endverbatim %}
'lex_raw_data' => '{'.
preg_quote($this->options['tag_block'][0], '#'). // {%
'('.
$this->options['whitespace_trim']. // -
'|'.
$this->options['whitespace_line_trim']. // ~
')?\s*endverbatim\s*'.
'(?:'.
preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*'. // -%}
'|'.
preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]*
'|'.
preg_quote($this->options['tag_block'][1], '#'). // %}
')
}sx',
'operator' => $this->getOperatorRegex(),
// #}
'lex_comment' => '{
(?:'.
preg_quote($this->options['whitespace_trim'].$this->options['tag_comment'][1], '#').'\s*\n?'. // -#}\s*\n?
'|'.
preg_quote($this->options['whitespace_line_trim'].$this->options['tag_comment'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~#}[ \t\0\x0B]*
'|'.
preg_quote($this->options['tag_comment'][1], '#').'\n?'. // #}\n?
')
}sx',
// verbatim %}
'lex_block_raw' => '{
\s*verbatim\s*
(?:'.
preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*'. // -%}\s*
'|'.
preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]*
'|'.
preg_quote($this->options['tag_block'][1], '#'). // %}
')
}Asx',
'lex_block_line' => '{\s*line\s+(\d+)\s*'.preg_quote($this->options['tag_block'][1], '#').'}As',
// {{ or {% or {#
'lex_tokens_start' => '{
('.
preg_quote($this->options['tag_variable'][0], '#'). // {{
'|'.
preg_quote($this->options['tag_block'][0], '#'). // {%
'|'.
preg_quote($this->options['tag_comment'][0], '#'). // {#
')('.
preg_quote($this->options['whitespace_trim'], '#'). // -
'|'.
preg_quote($this->options['whitespace_line_trim'], '#'). // ~
')?
}sx',
'interpolation_start' => '{'.preg_quote($this->options['interpolation'][0], '#').'\s*}A',
'interpolation_end' => '{\s*'.preg_quote($this->options['interpolation'][1], '#').'}A',
];
}
public function tokenize(Source $source): TokenStream
{
$this->source = $source;
$this->code = str_replace(["\r\n", "\r"], "\n", $source->getCode());
$this->cursor = 0;
$this->lineno = 1;
$this->end = \strlen($this->code);
$this->tokens = [];
$this->state = self::STATE_DATA;
$this->states = [];
$this->brackets = [];
$this->position = -1;
// find all token starts in one go
preg_match_all($this->regexes['lex_tokens_start'], $this->code, $matches, \PREG_OFFSET_CAPTURE);
$this->positions = $matches;
while ($this->cursor < $this->end) {
// dispatch to the lexing functions depending
// on the current state
switch ($this->state) {
case self::STATE_DATA:
$this->lexData();
break;
case self::STATE_BLOCK:
$this->lexBlock();
break;
case self::STATE_VAR:
$this->lexVar();
break;
case self::STATE_STRING:
$this->lexString();
break;
case self::STATE_INTERPOLATION:
$this->lexInterpolation();
break;
}
}
$this->pushToken(/* Token::EOF_TYPE */ -1);
if (!empty($this->brackets)) {
list($expect, $lineno) = array_pop($this->brackets);
throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source);
}
return new TokenStream($this->tokens, $this->source);
}
private function lexData(): void
{
// if no matches are left we return the rest of the template as simple text token
if ($this->position == \count($this->positions[0]) - 1) {
$this->pushToken(/* Token::TEXT_TYPE */ 0, substr($this->code, $this->cursor));
$this->cursor = $this->end;
return;
}
// Find the first token after the current cursor
$position = $this->positions[0][++$this->position];
while ($position[1] < $this->cursor) {
if ($this->position == \count($this->positions[0]) - 1) {
return;
}
$position = $this->positions[0][++$this->position];
}
// push the template text first
$text = $textContent = substr($this->code, $this->cursor, $position[1] - $this->cursor);
// trim?
if (isset($this->positions[2][$this->position][0])) {
if ($this->options['whitespace_trim'] === $this->positions[2][$this->position][0]) {
// whitespace_trim detected ({%-, {{- or {#-)
$text = rtrim($text);
} elseif ($this->options['whitespace_line_trim'] === $this->positions[2][$this->position][0]) {
// whitespace_line_trim detected ({%~, {{~ or {#~)
// don't trim \r and \n
$text = rtrim($text, " \t\0\x0B");
}
}
$this->pushToken(/* Token::TEXT_TYPE */ 0, $text);
$this->moveCursor($textContent.$position[0]);
switch ($this->positions[1][$this->position][0]) {
case $this->options['tag_comment'][0]:
$this->lexComment();
break;
case $this->options['tag_block'][0]:
// raw data?
if (preg_match($this->regexes['lex_block_raw'], $this->code, $match, 0, $this->cursor)) {
$this->moveCursor($match[0]);
$this->lexRawData();
// {% line \d+ %}
} elseif (preg_match($this->regexes['lex_block_line'], $this->code, $match, 0, $this->cursor)) {
$this->moveCursor($match[0]);
$this->lineno = (int) $match[1];
} else {
$this->pushToken(/* Token::BLOCK_START_TYPE */ 1);
$this->pushState(self::STATE_BLOCK);
$this->currentVarBlockLine = $this->lineno;
}
break;
case $this->options['tag_variable'][0]:
$this->pushToken(/* Token::VAR_START_TYPE */ 2);
$this->pushState(self::STATE_VAR);
$this->currentVarBlockLine = $this->lineno;
break;
}
}
private function lexBlock(): void
{
if (empty($this->brackets) && preg_match($this->regexes['lex_block'], $this->code, $match, 0, $this->cursor)) {
$this->pushToken(/* Token::BLOCK_END_TYPE */ 3);
$this->moveCursor($match[0]);
$this->popState();
} else {
$this->lexExpression();
}
}
private function lexVar(): void
{
if (empty($this->brackets) && preg_match($this->regexes['lex_var'], $this->code, $match, 0, $this->cursor)) {
$this->pushToken(/* Token::VAR_END_TYPE */ 4);
$this->moveCursor($match[0]);
$this->popState();
} else {
$this->lexExpression();
}
}
private function lexExpression(): void
{
// whitespace
if (preg_match('/\s+/A', $this->code, $match, 0, $this->cursor)) {
$this->moveCursor($match[0]);
if ($this->cursor >= $this->end) {
throw new SyntaxError(sprintf('Unclosed "%s".', self::STATE_BLOCK === $this->state ? 'block' : 'variable'), $this->currentVarBlockLine, $this->source);
}
}
// arrow function
if ('=' === $this->code[$this->cursor] && '>' === $this->code[$this->cursor + 1]) {
$this->pushToken(Token::ARROW_TYPE, '=>');
$this->moveCursor('=>');
}
// operators
elseif (preg_match($this->regexes['operator'], $this->code, $match, 0, $this->cursor)) {
$this->pushToken(/* Token::OPERATOR_TYPE */ 8, preg_replace('/\s+/', ' ', $match[0]));
$this->moveCursor($match[0]);
}
// names
elseif (preg_match(self::REGEX_NAME, $this->code, $match, 0, $this->cursor)) {
$this->pushToken(/* Token::NAME_TYPE */ 5, $match[0]);
$this->moveCursor($match[0]);
}
// numbers
elseif (preg_match(self::REGEX_NUMBER, $this->code, $match, 0, $this->cursor)) {
$number = (float) $match[0]; // floats
if (ctype_digit($match[0]) && $number <= \PHP_INT_MAX) {
$number = (int) $match[0]; // integers lower than the maximum
}
$this->pushToken(/* Token::NUMBER_TYPE */ 6, $number);
$this->moveCursor($match[0]);
}
// punctuation
elseif (false !== strpos(self::PUNCTUATION, $this->code[$this->cursor])) {
// opening bracket
if (false !== strpos('([{', $this->code[$this->cursor])) {
$this->brackets[] = [$this->code[$this->cursor], $this->lineno];
}
// closing bracket
elseif (false !== strpos(')]}', $this->code[$this->cursor])) {
if (empty($this->brackets)) {
throw new SyntaxError(sprintf('Unexpected "%s".', $this->code[$this->cursor]), $this->lineno, $this->source);
}
list($expect, $lineno) = array_pop($this->brackets);
if ($this->code[$this->cursor] != strtr($expect, '([{', ')]}')) {
throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source);
}
}
$this->pushToken(/* Token::PUNCTUATION_TYPE */ 9, $this->code[$this->cursor]);
++$this->cursor;
}
// strings
elseif (preg_match(self::REGEX_STRING, $this->code, $match, 0, $this->cursor)) {
$this->pushToken(/* Token::STRING_TYPE */ 7, stripcslashes(substr($match[0], 1, -1)));
$this->moveCursor($match[0]);
}
// opening double quoted string
elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, 0, $this->cursor)) {
$this->brackets[] = ['"', $this->lineno];
$this->pushState(self::STATE_STRING);
$this->moveCursor($match[0]);
}
// unlexable
else {
throw new SyntaxError(sprintf('Unexpected character "%s".', $this->code[$this->cursor]), $this->lineno, $this->source);
}
}
private function lexRawData(): void
{
if (!preg_match($this->regexes['lex_raw_data'], $this->code, $match, \PREG_OFFSET_CAPTURE, $this->cursor)) {
throw new SyntaxError('Unexpected end of file: Unclosed "verbatim" block.', $this->lineno, $this->source);
}
$text = substr($this->code, $this->cursor, $match[0][1] - $this->cursor);
$this->moveCursor($text.$match[0][0]);
// trim?
if (isset($match[1][0])) {
if ($this->options['whitespace_trim'] === $match[1][0]) {
// whitespace_trim detected ({%-, {{- or {#-)
$text = rtrim($text);
} else {
// whitespace_line_trim detected ({%~, {{~ or {#~)
// don't trim \r and \n
$text = rtrim($text, " \t\0\x0B");
}
}
$this->pushToken(/* Token::TEXT_TYPE */ 0, $text);
}
private function lexComment(): void
{
if (!preg_match($this->regexes['lex_comment'], $this->code, $match, \PREG_OFFSET_CAPTURE, $this->cursor)) {
throw new SyntaxError('Unclosed comment.', $this->lineno, $this->source);
}
$this->moveCursor(substr($this->code, $this->cursor, $match[0][1] - $this->cursor).$match[0][0]);
}
private function lexString(): void
{
if (preg_match($this->regexes['interpolation_start'], $this->code, $match, 0, $this->cursor)) {
$this->brackets[] = [$this->options['interpolation'][0], $this->lineno];
$this->pushToken(/* Token::INTERPOLATION_START_TYPE */ 10);
$this->moveCursor($match[0]);
$this->pushState(self::STATE_INTERPOLATION);
} elseif (preg_match(self::REGEX_DQ_STRING_PART, $this->code, $match, 0, $this->cursor) && \strlen($match[0]) > 0) {
$this->pushToken(/* Token::STRING_TYPE */ 7, stripcslashes($match[0]));
$this->moveCursor($match[0]);
} elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, 0, $this->cursor)) {
list($expect, $lineno) = array_pop($this->brackets);
if ('"' != $this->code[$this->cursor]) {
throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source);
}
$this->popState();
++$this->cursor;
} else {
// unlexable
throw new SyntaxError(sprintf('Unexpected character "%s".', $this->code[$this->cursor]), $this->lineno, $this->source);
}
}
private function lexInterpolation(): void
{
$bracket = end($this->brackets);
if ($this->options['interpolation'][0] === $bracket[0] && preg_match($this->regexes['interpolation_end'], $this->code, $match, 0, $this->cursor)) {
array_pop($this->brackets);
$this->pushToken(/* Token::INTERPOLATION_END_TYPE */ 11);
$this->moveCursor($match[0]);
$this->popState();
} else {
$this->lexExpression();
}
}
private function pushToken($type, $value = ''): void
{
// do not push empty text tokens
if (/* Token::TEXT_TYPE */ 0 === $type && '' === $value) {
return;
}
$this->tokens[] = new Token($type, $value, $this->lineno);
}
private function moveCursor($text): void
{
$this->cursor += \strlen($text);
$this->lineno += substr_count($text, "\n");
}
private function getOperatorRegex(): string
{
$operators = array_merge(
['='],
array_keys($this->env->getUnaryOperators()),
array_keys($this->env->getBinaryOperators())
);
$operators = array_combine($operators, array_map('strlen', $operators));
arsort($operators);
$regex = [];
foreach ($operators as $operator => $length) {
// an operator that ends with a character must be followed by
// a whitespace, a parenthesis, an opening map [ or sequence {
$r = preg_quote($operator, '/');
if (ctype_alpha($operator[$length - 1])) {
$r .= '(?=[\s()\[{])';
}
// an operator that begins with a character must not have a dot or pipe before
if (ctype_alpha($operator[0])) {
$r = '(?<![\.\|])'.$r;
}
// an operator with a space can be any amount of whitespaces
$r = preg_replace('/\s+/', '\s+', $r);
$regex[] = $r;
}
return '/'.implode('|', $regex).'/A';
}
private function pushState($state): void
{
$this->states[] = $this->state;
$this->state = $state;
}
private function popState(): void
{
if (0 === \count($this->states)) {
throw new \LogicException('Cannot pop state without a previous state.');
}
$this->state = array_pop($this->states);
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\SyntaxError;
use Twig\Node\BlockNode;
use Twig\Node\BlockReferenceNode;
use Twig\Node\BodyNode;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\MacroNode;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\Node\NodeCaptureInterface;
use Twig\Node\NodeOutputInterface;
use Twig\Node\PrintNode;
use Twig\Node\TextNode;
use Twig\TokenParser\TokenParserInterface;
/**
* @author Fabien Potencier <[email protected]>
*/
class Parser
{
private $stack = [];
private $stream;
private $parent;
private $visitors;
private $expressionParser;
private $blocks;
private $blockStack;
private $macros;
private $env;
private $importedSymbols;
private $traits;
private $embeddedTemplates = [];
private $varNameSalt = 0;
public function __construct(Environment $env)
{
$this->env = $env;
}
public function getVarName(): string
{
return sprintf('__internal_parse_%d', $this->varNameSalt++);
}
public function parse(TokenStream $stream, $test = null, bool $dropNeedle = false): ModuleNode
{
$vars = get_object_vars($this);
unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames'], $vars['varNameSalt']);
$this->stack[] = $vars;
// node visitors
if (null === $this->visitors) {
$this->visitors = $this->env->getNodeVisitors();
}
if (null === $this->expressionParser) {
$this->expressionParser = new ExpressionParser($this, $this->env);
}
$this->stream = $stream;
$this->parent = null;
$this->blocks = [];
$this->macros = [];
$this->traits = [];
$this->blockStack = [];
$this->importedSymbols = [[]];
$this->embeddedTemplates = [];
try {
$body = $this->subparse($test, $dropNeedle);
if (null !== $this->parent && null === $body = $this->filterBodyNodes($body)) {
$body = new Node();
}
} catch (SyntaxError $e) {
if (!$e->getSourceContext()) {
$e->setSourceContext($this->stream->getSourceContext());
}
if (!$e->getTemplateLine()) {
$e->setTemplateLine($this->stream->getCurrent()->getLine());
}
throw $e;
}
$node = new ModuleNode(new BodyNode([$body]), $this->parent, new Node($this->blocks), new Node($this->macros), new Node($this->traits), $this->embeddedTemplates, $stream->getSourceContext());
$traverser = new NodeTraverser($this->env, $this->visitors);
$node = $traverser->traverse($node);
// restore previous stack so previous parse() call can resume working
foreach (array_pop($this->stack) as $key => $val) {
$this->$key = $val;
}
return $node;
}
public function subparse($test, bool $dropNeedle = false): Node
{
$lineno = $this->getCurrentToken()->getLine();
$rv = [];
while (!$this->stream->isEOF()) {
switch ($this->getCurrentToken()->getType()) {
case /* Token::TEXT_TYPE */ 0:
$token = $this->stream->next();
$rv[] = new TextNode($token->getValue(), $token->getLine());
break;
case /* Token::VAR_START_TYPE */ 2:
$token = $this->stream->next();
$expr = $this->expressionParser->parseExpression();
$this->stream->expect(/* Token::VAR_END_TYPE */ 4);
$rv[] = new PrintNode($expr, $token->getLine());
break;
case /* Token::BLOCK_START_TYPE */ 1:
$this->stream->next();
$token = $this->getCurrentToken();
if (/* Token::NAME_TYPE */ 5 !== $token->getType()) {
throw new SyntaxError('A block must start with a tag name.', $token->getLine(), $this->stream->getSourceContext());
}
if (null !== $test && $test($token)) {
if ($dropNeedle) {
$this->stream->next();
}
if (1 === \count($rv)) {
return $rv[0];
}
return new Node($rv, [], $lineno);
}
if (!$subparser = $this->env->getTokenParser($token->getValue())) {
if (null !== $test) {
$e = new SyntaxError(sprintf('Unexpected "%s" tag', $token->getValue()), $token->getLine(), $this->stream->getSourceContext());
if (\is_array($test) && isset($test[0]) && $test[0] instanceof TokenParserInterface) {
$e->appendMessage(sprintf(' (expecting closing tag for the "%s" tag defined near line %s).', $test[0]->getTag(), $lineno));
}
} else {
$e = new SyntaxError(sprintf('Unknown "%s" tag.', $token->getValue()), $token->getLine(), $this->stream->getSourceContext());
$e->addSuggestions($token->getValue(), array_keys($this->env->getTokenParsers()));
}
throw $e;
}
$this->stream->next();
$subparser->setParser($this);
$node = $subparser->parse($token);
if (null !== $node) {
$rv[] = $node;
}
break;
default:
throw new SyntaxError('Lexer or parser ended up in unsupported state.', $this->getCurrentToken()->getLine(), $this->stream->getSourceContext());
}
}
if (1 === \count($rv)) {
return $rv[0];
}
return new Node($rv, [], $lineno);
}
public function getBlockStack(): array
{
return $this->blockStack;
}
public function peekBlockStack()
{
return $this->blockStack[\count($this->blockStack) - 1] ?? null;
}
public function popBlockStack(): void
{
array_pop($this->blockStack);
}
public function pushBlockStack($name): void
{
$this->blockStack[] = $name;
}
public function hasBlock(string $name): bool
{
return isset($this->blocks[$name]);
}
public function getBlock(string $name): Node
{
return $this->blocks[$name];
}
public function setBlock(string $name, BlockNode $value): void
{
$this->blocks[$name] = new BodyNode([$value], [], $value->getTemplateLine());
}
public function hasMacro(string $name): bool
{
return isset($this->macros[$name]);
}
public function setMacro(string $name, MacroNode $node): void
{
$this->macros[$name] = $node;
}
public function addTrait($trait): void
{
$this->traits[] = $trait;
}
public function hasTraits(): bool
{
return \count($this->traits) > 0;
}
public function embedTemplate(ModuleNode $template)
{
$template->setIndex(mt_rand());
$this->embeddedTemplates[] = $template;
}
public function addImportedSymbol(string $type, string $alias, string $name = null, AbstractExpression $node = null): void
{
$this->importedSymbols[0][$type][$alias] = ['name' => $name, 'node' => $node];
}
public function getImportedSymbol(string $type, string $alias)
{
// if the symbol does not exist in the current scope (0), try in the main/global scope (last index)
return $this->importedSymbols[0][$type][$alias] ?? ($this->importedSymbols[\count($this->importedSymbols) - 1][$type][$alias] ?? null);
}
public function isMainScope(): bool
{
return 1 === \count($this->importedSymbols);
}
public function pushLocalScope(): void
{
array_unshift($this->importedSymbols, []);
}
public function popLocalScope(): void
{
array_shift($this->importedSymbols);
}
public function getExpressionParser(): ExpressionParser
{
return $this->expressionParser;
}
public function getParent(): ?Node
{
return $this->parent;
}
public function setParent(?Node $parent): void
{
$this->parent = $parent;
}
public function getStream(): TokenStream
{
return $this->stream;
}
public function getCurrentToken(): Token
{
return $this->stream->getCurrent();
}
private function filterBodyNodes(Node $node, bool $nested = false): ?Node
{
// check that the body does not contain non-empty output nodes
if (
($node instanceof TextNode && !ctype_space($node->getAttribute('data')))
||
(!$node instanceof TextNode && !$node instanceof BlockReferenceNode && $node instanceof NodeOutputInterface)
) {
if (false !== strpos((string) $node, \chr(0xEF).\chr(0xBB).\chr(0xBF))) {
$t = substr($node->getAttribute('data'), 3);
if ('' === $t || ctype_space($t)) {
// bypass empty nodes starting with a BOM
return null;
}
}
throw new SyntaxError('A template that extends another one cannot include content outside Twig blocks. Did you forget to put the content inside a {% block %} tag?', $node->getTemplateLine(), $this->stream->getSourceContext());
}
// bypass nodes that "capture" the output
if ($node instanceof NodeCaptureInterface) {
// a "block" tag in such a node will serve as a block definition AND be displayed in place as well
return $node;
}
// "block" tags that are not captured (see above) are only used for defining
// the content of the block. In such a case, nesting it does not work as
// expected as the definition is not part of the default template code flow.
if ($nested && $node instanceof BlockReferenceNode) {
throw new SyntaxError('A block definition cannot be nested under non-capturing nodes.', $node->getTemplateLine(), $this->stream->getSourceContext());
}
if ($node instanceof NodeOutputInterface) {
return null;
}
// here, $nested means "being at the root level of a child template"
// we need to discard the wrapping "Node" for the "body" node
$nested = $nested || Node::class !== \get_class($node);
foreach ($node as $k => $n) {
if (null !== $n && null === $this->filterBodyNodes($n, $nested)) {
$node->removeNode($k);
}
}
return $node;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?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\RuntimeLoader;
use Psr\Container\ContainerInterface;
/**
* Lazily loads Twig runtime implementations from a PSR-11 container.
*
* Note that the runtime services MUST use their class names as identifiers.
*
* @author Fabien Potencier <[email protected]>
* @author Robin Chalas <[email protected]>
*/
class ContainerRuntimeLoader implements RuntimeLoaderInterface
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function load(string $class)
{
return $this->container->has($class) ? $this->container->get($class) : null;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.