本文整理汇总了PHP中head函数的典型用法代码示例。如果您正苦于以下问题:PHP head函数的具体用法?PHP head怎么用?PHP head使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了head函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: execute
protected function execute(ConduitAPIRequest $request)
{
$corpus = $request->getValue('corpus');
$aux_fields = DifferentialFieldSelector::newSelector()->getFieldSpecifications();
foreach ($aux_fields as $key => $aux_field) {
if (!$aux_field->shouldAppearOnCommitMessage()) {
unset($aux_fields[$key]);
}
}
$aux_fields = mpull($aux_fields, null, 'getCommitMessageKey');
// Build a map from labels (like "Test Plan") to field keys
// (like "testPlan").
$label_map = $this->buildLabelMap($aux_fields);
$field_map = $this->parseCommitMessage($corpus, $label_map);
$fields = array();
$errors = array();
foreach ($field_map as $field_key => $field_value) {
$field = $aux_fields[$field_key];
try {
$fields[$field_key] = $field->parseValueFromCommitMessage($field_value);
} catch (DifferentialFieldParseException $ex) {
$field_label = $field->renderLabelForCommitMessage();
$errors[] = "Error parsing field '{$field_label}': " . $ex->getMessage();
}
}
// TODO: This is for backcompat only, remove once Arcanist gets updated.
$error = head($errors);
return array('error' => $error, 'errors' => $errors, 'fields' => $fields);
}
示例2: processMailCommands
private function processMailCommands(PhabricatorMetaMTAReceivedMail $mail, array $command_list)
{
$viewer = $this->getActor();
$object = $this->getMailReceiver();
$list = MetaMTAEmailTransactionCommand::getAllCommandsForObject($object);
$map = MetaMTAEmailTransactionCommand::getCommandMap($list);
$xactions = array();
foreach ($command_list as $command_argv) {
$command = head($command_argv);
$argv = array_slice($command_argv, 1);
$handler = idx($map, phutil_utf8_strtolower($command));
if ($handler) {
$results = $handler->buildTransactions($viewer, $object, $mail, $command, $argv);
foreach ($results as $result) {
$xactions[] = $result;
}
} else {
$valid_commands = array();
foreach ($list as $valid_command) {
$aliases = $valid_command->getCommandAliases();
if ($aliases) {
foreach ($aliases as $key => $alias) {
$aliases[$key] = '!' . $alias;
}
$aliases = implode(', ', $aliases);
$valid_commands[] = pht('!%s (or %s)', $valid_command->getCommand(), $aliases);
} else {
$valid_commands[] = '!' . $valid_command->getCommand();
}
}
throw new Exception(pht('The command "!%s" is not a supported mail command. Valid ' . 'commands for this object are: %s.', $command, implode(', ', $valid_commands)));
}
}
return $xactions;
}
示例3: execute
public function execute(PhutilArgumentParser $args)
{
$emails = $args->getArg('email');
if (!$emails) {
throw new PhutilArgumentUsageException(pht('You must specify the email to verify.'));
} else {
if (count($emails) > 1) {
throw new PhutilArgumentUsageException(pht('You can only verify one address at a time.'));
}
}
$address = head($emails);
$email = id(new PhabricatorUserEmail())->loadOneWhere('address = %s', $address);
if (!$email) {
throw new PhutilArgumentUsageException(pht('No email exists with address "%s"!', $address));
}
$viewer = $this->getViewer();
$user = id(new PhabricatorPeopleQuery())->setViewer($viewer)->withPHIDs(array($email->getUserPHID()))->executeOne();
if (!$user) {
throw new Exception(pht('Email record has invalid user PHID!'));
}
$editor = id(new PhabricatorUserEditor())->setActor($viewer)->verifyEmail($user, $email);
$console = PhutilConsole::getConsole();
$console->writeOut("%s\n", pht('Done.'));
return 0;
}
示例4: getLog
public static function getLog()
{
if (!self::$log) {
$path = PhabricatorEnv::getEnvConfig('log.ssh.path');
$format = PhabricatorEnv::getEnvConfig('log.ssh.format');
$format = nonempty($format, "[%D]\t%p\t%h\t%r\t%s\t%S\t%u\t%C\t%U\t%c\t%T\t%i\t%o");
// NOTE: Path may be null. We still create the log, it just won't write
// anywhere.
$data = array('D' => date('r'), 'h' => php_uname('n'), 'p' => getmypid(), 'e' => time());
$sudo_user = PhabricatorEnv::getEnvConfig('phd.user');
if (strlen($sudo_user)) {
$data['S'] = $sudo_user;
}
if (function_exists('posix_geteuid')) {
$system_uid = posix_geteuid();
$system_info = posix_getpwuid($system_uid);
$data['s'] = idx($system_info, 'name');
}
$client = getenv('SSH_CLIENT');
if (strlen($client)) {
$remote_address = head(explode(' ', $client));
$data['r'] = $remote_address;
}
$log = id(new PhutilDeferredLog($path, $format))->setFailQuietly(true)->setData($data);
self::$log = $log;
}
return self::$log;
}
示例5: doLock
protected function doLock($wait)
{
$conn = $this->conn;
if (!$conn) {
// Try to reuse a connection from the connection pool.
$conn = array_pop(self::$pool);
}
if (!$conn) {
// NOTE: Using the 'repository' database somewhat arbitrarily, mostly
// because the first client of locks is the repository daemons. We must
// always use the same database for all locks, but don't access any
// tables so we could use any valid database. We could build a
// database-free connection instead, but that's kind of messy and we
// might forget about it in the future if we vertically partition the
// application.
$dao = new PhabricatorRepository();
// NOTE: Using "force_new" to make sure each lock is on its own
// connection.
$conn = $dao->establishConnection('w', $force_new = true);
// NOTE: Since MySQL will disconnect us if we're idle for too long, we set
// the wait_timeout to an enormous value, to allow us to hold the
// connection open indefinitely (or, at least, for 24 days).
$max_allowed_timeout = 2147483;
queryfx($conn, 'SET wait_timeout = %d', $max_allowed_timeout);
}
$result = queryfx_one($conn, 'SELECT GET_LOCK(%s, %f)', 'phabricator:' . $this->lockname, $wait);
$ok = head($result);
if (!$ok) {
throw new PhutilLockException($this->getName());
}
$this->conn = $conn;
}
示例6: getRouteInformation
/**
* Get the route information for a given route.
*
* @param \Illuminate\Routing\Route $route
* @return array
*/
protected function getRouteInformation($route)
{
if (!is_a($route, 'Illuminate\\Routing\\Route')) {
return array();
}
$uri = head($route->methods()) . ' ' . $route->uri();
$action = $route->getAction();
$result = array('uri' => $uri ?: '-');
$result = array_merge($result, $action);
if (isset($action['controller']) && strpos($action['controller'], '@') !== false) {
list($controller, $method) = explode('@', $action['controller']);
if (class_exists($controller) && method_exists($controller, $method)) {
$reflector = new \ReflectionMethod($controller, $method);
}
unset($result['uses']);
} elseif (isset($action['uses']) && $action['uses'] instanceof \Closure) {
$reflector = new \ReflectionFunction($action['uses']);
$result['uses'] = $this->formatVar($result['uses']);
}
if (isset($reflector)) {
$filename = ltrim(str_replace(base_path(), '', $reflector->getFileName()), '/');
$result['file'] = $filename . ':' . $reflector->getStartLine() . '-' . $reflector->getEndLine();
}
if ($before = $this->getBeforeFilters($route)) {
$result['before'] = $before;
}
if ($after = $this->getAfterFilters($route)) {
$result['after'] = $after;
}
return $result;
}
示例7: handleRequest
public function handleRequest(AphrontRequest $request)
{
$viewer = $request->getViewer();
$stories = id(new PhabricatorNotificationQuery())->setViewer($viewer)->withUserPHIDs(array($viewer->getPHID()))->withKeys(array($request->getStr('key')))->execute();
if (!$stories) {
return $this->buildEmptyResponse();
}
$story = head($stories);
if ($story->getAuthorPHID() === $viewer->getPHID()) {
// Don't show the user individual notifications about their own
// actions. Primarily, this stops pages from showing notifications
// immediately after you click "Submit" on a comment form if the
// notification server returns faster than the web server.
// TODO: It would be nice to retain the "page updated" bubble on copies
// of the page that are open in other tabs, but there isn't an obvious
// way to do this easily.
return $this->buildEmptyResponse();
}
$builder = id(new PhabricatorNotificationBuilder(array($story)))->setUser($viewer)->setShowTimestamps(false);
$content = $builder->buildView()->render();
$dict = $builder->buildDict();
$data = $dict[0];
$response = array('pertinent' => true, 'primaryObjectPHID' => $story->getPrimaryObjectPHID(), 'desktopReady' => $data['desktopReady'], 'href' => $data['href'], 'icon' => $data['icon'], 'title' => $data['title'], 'body' => $data['body'], 'content' => hsprintf('%s', $content));
return id(new AphrontAjaxResponse())->setContent($response);
}
示例8: execute
public function execute(HarbormasterBuild $build, HarbormasterBuildTarget $build_target)
{
// We can only wait when building against commits.
$buildable = $build->getBuildable();
$object = $buildable->getBuildableObject();
if (!$object instanceof PhabricatorRepositoryCommit) {
return;
}
// Block until all previous builds of the same build plan have
// finished.
$plan = $build->getBuildPlan();
$existing_logs = id(new HarbormasterBuildLogQuery())->setViewer(PhabricatorUser::getOmnipotentUser())->withBuildTargetPHIDs(array($build_target->getPHID()))->execute();
if ($existing_logs) {
$log = head($existing_logs);
} else {
$log = $build->createLog($build_target, 'waiting', 'blockers');
}
$blockers = $this->getBlockers($object, $plan, $build);
if ($blockers) {
$log->start();
$log->append(pht("Blocked by: %s\n", implode(',', $blockers)));
$log->finalize();
}
if ($blockers) {
throw new PhabricatorWorkerYieldException(15);
}
}
示例9: execute
public function execute(PhutilArgumentParser $args)
{
$viewer = $this->getViewer();
$argv = $args->getArg('argv');
if (count($argv) !== 2) {
throw new PhutilArgumentUsageException(pht('Specify a commit and a revision to attach it to.'));
}
$commit_name = head($argv);
$revision_name = last($argv);
$commit = id(new DiffusionCommitQuery())->setViewer($viewer)->withIdentifiers(array($commit_name))->executeOne();
if (!$commit) {
throw new PhutilArgumentUsageException(pht('Commit "%s" does not exist.', $commit_name));
}
$revision = id(new PhabricatorObjectQuery())->setViewer($viewer)->withNames(array($revision_name))->executeOne();
if (!$revision) {
throw new PhutilArgumentUsageException(pht('Revision "%s" does not exist.', $revision_name));
}
if (!$revision instanceof DifferentialRevision) {
throw new PhutilArgumentUsageException(pht('Object "%s" must be a Differential revision.', $revision_name));
}
// Reload the revision to get the active diff.
$revision = id(new DifferentialRevisionQuery())->setViewer($viewer)->withIDs(array($revision->getID()))->needActiveDiffs(true)->executeOne();
$differential_phid = id(new PhabricatorDifferentialApplication())->getPHID();
$extraction_engine = id(new DifferentialDiffExtractionEngine())->setViewer($viewer)->setAuthorPHID($differential_phid);
$content_source = PhabricatorContentSource::newForSource(PhabricatorContentSource::SOURCE_CONSOLE, array());
$extraction_engine->updateRevisionWithCommit($revision, $commit, array(), $content_source);
echo tsprintf("%s\n", pht('Attached "%s" to "%s".', $commit->getMonogram(), $revision->getMonogram()));
}
示例10: reduceProxyResponse
public function reduceProxyResponse()
{
if ($this->transactionView) {
$view = $this->transactionView;
} else {
if ($this->getTransactions()) {
$view = head($this->getTransactions())->getApplicationTransactionViewObject();
} else {
$view = new PhabricatorApplicationTransactionView();
}
}
$view->setUser($this->getViewer())->setTransactions($this->getTransactions())->setIsPreview($this->isPreview);
if ($this->isPreview) {
$xactions = mpull($view->buildEvents(), 'render');
} else {
$xactions = mpull($view->buildEvents(), 'render', 'getTransactionPHID');
}
// Force whatever the underlying views built to render into HTML for
// the Javascript.
foreach ($xactions as $key => $xaction) {
$xactions[$key] = hsprintf('%s', $xaction);
}
$content = array('xactions' => $xactions, 'spacer' => PHUITimelineView::renderSpacer());
return $this->getProxy()->setContent($content);
}
示例11: compose
/**
* Bind data to the view.
*
* @param View $view
*
* @return void
*/
public function compose(View $view)
{
$data = $view->getData();
if (Auth::check()) {
$notifications = Auth::user()->notifications()->with('user')->orderBy('created_at', 'desc')->take(15)->get();
$view->with('notifications', $notifications);
$unreadCount = Auth::user()->notifications()->wherePivot('read', false)->count();
$view->with('newNotificationsCount', $unreadCount);
}
// Get object from which we can extract name to use as page title
$currentGroup = head(array_only($data, ['group', 'folder', 'fakeGroup']));
$view->with('currentGroup', $currentGroup);
if (isset($currentGroup) && isset($currentGroup->name)) {
$pageTitle = $currentGroup->name;
// Homepage title shall always be Strimoid.pl
if ($currentGroup->urlname == 'all' && !Setting::get('homepage_subscribed', false)) {
$pageTitle = 'Strimoid';
}
if ($currentGroup->urlname == 'subscribed' && Setting::get('homepage_subscribed', false)) {
$pageTitle = 'Strimoid';
}
} else {
$pageTitle = 'Strimoid';
}
$view->with('pageTitle', $pageTitle);
// Needed by top bar with groups
$popularGroups = Cache::remember('popularGroups', 60, function () {
return Group::orderBy('subscribers_count', 'desc', true)->take(30)->get(['id', 'name', 'urlname']);
});
$view->with('popularGroups', $popularGroups);
}
示例12: sortMiddleware
/**
* Sort the middlewares by the given priority map.
*
* Each call to this method makes one discrete middleware movement if necessary.
*
* @param array $priorityMap
* @param array $middlewares
* @return array
*/
protected function sortMiddleware($priorityMap, $middlewares)
{
$lastIndex = 0;
foreach ($middlewares as $index => $middleware) {
if (!is_string($middleware)) {
continue;
}
$stripped = head(explode(':', $middleware));
if (in_array($stripped, $priorityMap)) {
$priorityIndex = array_search($stripped, $priorityMap);
// This middleware is in the priority map. If we have encountered another middleware
// that was also in the priority map and was at a lower priority than the current
// middleware, we will move this middleware to be above the previous encounter.
if (isset($lastPriorityIndex) && $priorityIndex < $lastPriorityIndex) {
return $this->sortMiddleware($priorityMap, array_values($this->moveMiddleware($middlewares, $index, $lastIndex)));
// This middleware is in the priority map; but, this is the first middleware we have
// encountered from the map thus far. We'll save its current index plus its index
// from the priority map so we can compare against them on the next iterations.
} else {
$lastIndex = $index;
$lastPriorityIndex = $priorityIndex;
}
}
}
return array_values(array_unique($middlewares, SORT_REGULAR));
}
示例13: __call
/**
* It's magic!
*
* @param string $method
* @param array $arguments
*
* @throws \Exception
*
* @return array|string
*/
public function __call(string $method, array $arguments)
{
if (in_array($httpMethod = strtoupper($method), $this->methodMap)) {
return $this->request($httpMethod, head($arguments));
}
throw new \Exception('Method "' . $method . '" does not exist.');
}
示例14: setCommonVariable
protected function setCommonVariable()
{
// Achieve that segment
$this->accessUrl = config('cmsharenjoy.access_url');
// Get the action name
$routeArray = Str::parseCallback(Route::currentRouteAction(), null);
if (last($routeArray) != null) {
// Remove 'controller' from the controller name.
$controller = str_replace('Controller', '', class_basename(head($routeArray)));
// Take out the method from the action.
$action = str_replace(['get', 'post', 'patch', 'put', 'delete'], '', last($routeArray));
// post, report
$this->onController = strtolower($controller);
session()->put('onController', $this->onController);
view()->share('onController', $this->onController);
// get-create, post-create
$this->onMethod = Str::slug(Request::method() . '-' . $action);
session()->put('onMethod', $this->onMethod);
view()->share('onMethod', $this->onMethod);
// create, update
$this->onAction = strtolower($action);
session()->put('onAction', $this->onAction);
view()->share('onAction', $this->onAction);
}
// Brand name from setting
$this->brandName = Setting::get('brand_name');
// Share some variables to views
view()->share('brandName', $this->brandName);
view()->share('langLocales', config('cmsharenjoy.locales'));
view()->share('activeLanguage', session('sharenjoy.backEndLanguage'));
// Set the theme
// $this->theme = Theme::uses('front');
// Message
view()->share('messages', Message::getMessageBag());
}
示例15: buildBareRepository
protected function buildBareRepository($callsign)
{
$existing_repository = id(new PhabricatorRepositoryQuery())->withCallsigns(array($callsign))->setViewer(PhabricatorUser::getOmnipotentUser())->executeOne();
if ($existing_repository) {
$existing_repository->delete();
}
$data_dir = dirname(__FILE__) . '/data/';
$types = array('svn' => PhabricatorRepositoryType::REPOSITORY_TYPE_SVN, 'hg' => PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL, 'git' => PhabricatorRepositoryType::REPOSITORY_TYPE_GIT);
$hits = array();
foreach ($types as $type => $const) {
$path = $data_dir . $callsign . '.' . $type . '.tgz';
if (Filesystem::pathExists($path)) {
$hits[$const] = $path;
}
}
if (!$hits) {
throw new Exception("No test data for callsign '{$callsign}'. Expected an archive " . "like '{$callsign}.git.tgz' in '{$data_dir}'.");
}
if (count($hits) > 1) {
throw new Exception("Expected exactly one archive matching callsign '{$callsign}', " . "found too many: " . implode(', ', $hits));
}
$path = head($hits);
$vcs_type = head_key($hits);
$dir = PhutilDirectoryFixture::newFromArchive($path);
$local = new TempFile('.ignore');
$user = $this->generateNewTestUser();
$repo = PhabricatorRepository::initializeNewRepository($user)->setCallsign($callsign)->setName(pht('Test Repo "%s"', $callsign))->setVersionControlSystem($vcs_type)->setDetail('local-path', dirname($local) . '/' . $callsign)->setDetail('remote-uri', 'file://' . $dir->getPath() . '/');
$this->didConstructRepository($repo);
$repo->save();
$repo->makeEphemeral();
// Keep the disk resources around until we exit.
$this->dirs[] = $dir;
$this->dirs[] = $local;
return $repo;
}