[ENTITY] Rename 'getFrom' to 'getBy'

This commit is contained in:
Hugo Sales 2021-12-04 19:58:00 +00:00
parent c40866ecf6
commit e29e1cc87c
No known key found for this signature in database
GPG Key ID: 7D0C7EAFC9D835A0
15 changed files with 110 additions and 96 deletions

View File

@ -181,7 +181,7 @@ class Posting extends Component
'content' => $content,
'content_type' => $content_type,
'rendered' => $rendered,
'language_id' => Language::getFromLocale($language)->getId(),
'language_id' => Language::getByLocale($language)->getId(),
'is_local' => true,
]);

View File

@ -74,7 +74,7 @@ class Tag extends Component
preg_match_all(self::TAG_REGEX, $content, $matched_tags, \PREG_SET_ORDER);
foreach ($matched_tags as $match) {
$tag = self::ensureValid($match[2]);
$canonical_tag = self::canonicalTag($tag, Language::getFromId($note->getLanguageId())->getLocale());
$canonical_tag = self::canonicalTag($tag, Language::getById($note->getLanguageId())->getLocale());
DB::persist(NoteTag::create([
'tag' => $tag,
'canonical' => $canonical_tag,

View File

@ -65,24 +65,24 @@ class Note extends Model
*/
public static function fromJson(string|AbstractObject $json, array $options = []): GSNote
{
$source = $options['source'];
$source = $options['source'];
$actor_uri = $options['actor_uri'];
$actor_id = $options['actor_id'];
$type_note = is_string($json) ? self::jsonToType($json) : $json;
$actor_id = $options['actor_id'];
$type_note = \is_string($json) ? self::jsonToType($json) : $json;
if (is_null($actor_uri) || $actor_uri !== $type_note->get('attributedTo')) {
if (\is_null($actor_uri) || $actor_uri !== $type_note->get('attributedTo')) {
$actor_id = ActivityPub::getActorByUri($type_note->get('attributedTo'))->getId();
}
$map = [
'is_local' => false,
'created' => new DateTime($type_note->get('published') ?? 'now'),
'content' => $type_note->get('content') ?? null,
'is_local' => false,
'created' => new DateTime($type_note->get('published') ?? 'now'),
'content' => $type_note->get('content') ?? null,
'content_type' => 'text/html',
'language_id' => $type_note->get('contentLang') ?? null,
'url' => $type_note->get('url') ?? $type_note->get('id'),
'actor_id' => $actor_id,
'modified' => new DateTime(),
'source' => $source,
'language_id' => $type_note->get('contentLang') ?? null,
'url' => $type_note->get('url') ?? $type_note->get('id'),
'actor_id' => $actor_id,
'modified' => new DateTime(),
'source' => $source,
];
if ($map['content'] !== null) {
$mentions = [];
@ -98,8 +98,8 @@ class Note extends Model
$obj = new GSNote();
if (!is_null($map['language_id'])) {
$map['language_id'] = Language::getFromLocale($map['language_id'])->getId();
if (!\is_null($map['language_id'])) {
$map['language_id'] = Language::getByLocale($map['language_id'])->getId();
} else {
$map['language_id'] = null;
}
@ -128,13 +128,13 @@ class Note extends Model
}
$attr = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'id' => Router::url('note_view', ['id' => $object->getId()], Router::ABSOLUTE_URL),
'published' => $object->getCreated()->format(DateTimeInterface::RFC3339),
'@context' => 'https://www.w3.org/ns/activitystreams',
'id' => Router::url('note_view', ['id' => $object->getId()], Router::ABSOLUTE_URL),
'published' => $object->getCreated()->format(DateTimeInterface::RFC3339),
'attributedTo' => $object->getActor()->getUri(Router::ABSOLUTE_URL),
'to' => ['https://www.w3.org/ns/activitystreams#Public'], // TODO: implement proper scope address
'cc' => ['https://www.w3.org/ns/activitystreams#Public'],
'content' => $object->getRendered(),
'to' => ['https://www.w3.org/ns/activitystreams#Public'], // TODO: implement proper scope address
'cc' => ['https://www.w3.org/ns/activitystreams#Public'],
'content' => $object->getRendered(),
//'tag' => $tags
];
@ -142,4 +142,4 @@ class Note extends Model
Event::handle('ActivityPubAddActivityStreamsTwoData', [$type->get('type'), &$type]);
return $type->toJson($options);
}
}
}

View File

@ -91,7 +91,7 @@ class Repeat extends Controller
actor: Actor::getById($actor_id),
content: $note->getContent(),
content_type: $note->getContentType(),
language: Language::getFromId($note->getLanguageId())->getLocale(),
language: Language::getById($note->getLanguageId())->getLocale(),
processed_attachments: $note->getAttachmentsWithTitle(),
);

View File

@ -52,9 +52,9 @@ class TagBasedFiltering extends Controller
public function editBlockedNoteTags(Request $request, ?int $note_id)
{
$user = Common::ensureLoggedIn();
$note = !\is_null($note_id) ? Note::getFromId($note_id) : null;
$note_tag_blocks = NoteTagBlock::getFromActorId($user->getId());
$note_tags = !\is_null($note_id) ? NoteTag::getFromNoteId($note_id) : [];
$note = !\is_null($note_id) ? Note::getById($note_id) : null;
$note_tag_blocks = NoteTagBlock::getByActorId($user->getId());
$note_tags = !\is_null($note_id) ? NoteTag::getByNoteId($note_id) : [];
$blockable_note_tags = F\reject(
$note_tags,
fn (NoteTag $nt) => NoteTagBlock::checkBlocksNoteTag($nt, $note_tag_blocks),
@ -92,7 +92,7 @@ class TagBasedFiltering extends Controller
Cache::delete(NoteTagBlock::cacheKey($user->getId()));
Cache::delete(TagFilerPlugin::cacheKeys($user->getId())['note']);
$new_tag = Tag::ensureValid($data[$canon . ':new-tag']);
$canonical_tag = Tag::canonicalTag($new_tag, Language::getFromNote($note)->getLocale());
$canonical_tag = Tag::canonicalTag($new_tag, Language::getByNote($note)->getLocale());
DB::persist(NoteTagBlock::create([
'blocker' => $user->getId(),
'tag' => $new_tag,
@ -140,7 +140,7 @@ class TagBasedFiltering extends Controller
return [
'_template' => 'tag-based-filtering/edit-tags.html.twig',
'note' => !\is_null($note_id) ? Note::getFromId($note_id) : null,
'note' => !\is_null($note_id) ? Note::getById($note_id) : null,
'new_tags_form' => $new_tags_form?->createView(),
'existing_tags_form' => $existing_tags_form?->createView(),
];

View File

@ -82,7 +82,7 @@ class TagBasedFiltering extends Plugin
$notes_out = F\reject(
$notes,
fn (Note $n) => F\some(
dump(NoteTag::getFromNoteId($n->getId())),
dump(NoteTag::getByNoteId($n->getId())),
fn ($nt) => NoteTagBlock::checkBlocksNoteTag($nt, $blocked_note_tags),
),
);

View File

@ -1,6 +1,6 @@
<?php
declare(strict_types=1);
declare(strict_types = 1);
// {{{ License
@ -42,6 +42,7 @@ use App\Core\Controller;
use App\Core\DB\DB;
use App\Core\Event;
use App\Core\Form;
use function App\Core\I18n\_m;
use App\Core\Log;
use App\Entity\ActorLanguage;
use App\Entity\Language;
@ -73,8 +74,6 @@ use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\SubmitButton;
use Symfony\Component\HttpFoundation\Request;
use function App\Core\I18n\_m;
use function is_null;
// }}} Imports
@ -88,28 +87,26 @@ class UserPanel extends Controller
public function allSettings(Request $request): array
{
$personal_form = $this->personalInfo($request);
$email_form = $this->email($request);
$email_form = $this->email($request);
$password_form = $this->password($request);
$language_form = $this->language($request);
$notifications_form_array = $this->notifications($request);
return [
'_template' => 'settings/base.html.twig',
'profile' => $personal_form->createView(),
'email' => $email_form->createView(),
'password' => $password_form->createView(),
'language' => $language_form->createView(),
'_template' => 'settings/base.html.twig',
'profile' => $personal_form->createView(),
'email' => $email_form->createView(),
'password' => $password_form->createView(),
'language' => $language_form->createView(),
'tabbed_forms_notify' => $notifications_form_array,
'open_details_query' => $this->string('open'),
'open_details_query' => $this->string('open'),
];
}
/**
* Change email settings form
*
* @param Request $request
* @return FormInterface
* @throws NoLoggedInUser
* @throws ServerException
*/
@ -142,8 +139,6 @@ class UserPanel extends Controller
/**
* Change password form
*
* @param Request $request
* @return FormInterface
* @throws AuthenticationException
* @throws NoLoggedInUser
* @throws ServerException
@ -162,7 +157,7 @@ class UserPanel extends Controller
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
if (!is_null($data['old_password'])) {
if (!\is_null($data['old_password'])) {
$data['password'] = $form->get('password')->getData();
if (!($user->changePassword($data['old_password'], $data['password']))) {
throw new AuthenticationException(_m('The provided password is incorrect'));
@ -182,9 +177,9 @@ class UserPanel extends Controller
}
/**
* @throws NoLoggedInUser
* @throws RedirectException
* @throws ServerException
* @throws NoLoggedInUser
*/
public function language(Request $request): FormInterface
{
@ -227,7 +222,6 @@ class UserPanel extends Controller
throw new RedirectException('settings_sort_languages', ['_fragment' => null]); // TODO doesn't clear fragment
}
}
return $form;
}
@ -235,8 +229,6 @@ class UserPanel extends Controller
/**
* Local user personal information panel
*
* @param Request $request
* @return mixed
* @throws NicknameEmptyException
* @throws NicknameInvalidException
* @throws NicknameNotAllowedException
@ -248,12 +240,12 @@ class UserPanel extends Controller
public function personalInfo(Request $request): mixed
{
// Ensure the user is logged in and retrieve Actor object for given user
$user = Common::ensureLoggedIn();
$user = Common::ensureLoggedIn();
$actor = $user->getActor();
// Used in Form::handle as an array $extra_args
[$_, $actor_tags] = $actor->getSelfTags();
$extra = ['self_tags' => $actor_tags];
$extra = ['self_tags' => $actor_tags];
// Defining the various form fields
$form_definition = [
@ -279,33 +271,33 @@ class UserPanel extends Controller
*/
public function notifications(Request $request): array
{
$user = Common::ensureLoggedIn();
$schema = DB::getConnection()->getSchemaManager();
$platform = $schema->getDatabasePlatform();
$columns = Common::arrayRemoveKeys($schema->listTableColumns('user_notification_prefs'), ['user_id', 'transport', 'created', 'modified']);
$user = Common::ensureLoggedIn();
$schema = DB::getConnection()->getSchemaManager();
$platform = $schema->getDatabasePlatform();
$columns = Common::arrayRemoveKeys($schema->listTableColumns('user_notification_prefs'), ['user_id', 'transport', 'created', 'modified']);
$form_defs = ['placeholder' => []];
foreach ($columns as $name => $col) {
$type = $col->getType();
$val = $type->convertToPHPValue($col->getDefault(), $platform);
$type = $col->getType();
$val = $type->convertToPHPValue($col->getDefault(), $platform);
$type_str = $type->getName();
$label = str_replace('_', ' ', ucfirst($name));
$label = str_replace('_', ' ', ucfirst($name));
$labels = [
'target_actor_id' => 'Target Actors',
'dm' => 'DM',
'dm' => 'DM',
];
$help = [
'target_actor_id' => 'If specified, these settings apply only to these profiles (comma- or space-separated list)',
'target_actor_id' => 'If specified, these settings apply only to these profiles (comma- or space-separated list)',
'activity_by_subscribed' => 'Notify me when someone I subscribed has new activity',
'mention' => 'Notify me when mentions me in a notice',
'reply' => 'Notify me when someone replies to a notice made by me',
'subscription' => 'Notify me when someone subscribes to me or asks for permission to do so',
'favorite' => 'Notify me when someone favorites one of my notices',
'nudge' => 'Notify me when someone nudges me',
'dm' => 'Notify me when someone sends me a direct message',
'post_on_status_change' => 'Post a notice when my status in this service changes',
'enable_posting' => 'Enable posting from this service',
'mention' => 'Notify me when mentions me in a notice',
'reply' => 'Notify me when someone replies to a notice made by me',
'subscription' => 'Notify me when someone subscribes to me or asks for permission to do so',
'favorite' => 'Notify me when someone favorites one of my notices',
'nudge' => 'Notify me when someone nudges me',
'dm' => 'Notify me when someone sends me a direct message',
'post_on_status_change' => 'Post a notice when my status in this service changes',
'enable_posting' => 'Enable posting from this service',
];
switch ($type_str) {
@ -325,8 +317,8 @@ class UserPanel extends Controller
}
}
$form_defs['placeholder']['save'] = fn(string $transport, string $form_name) => [$form_name, SubmitType::class,
['label' => _m('Save notification settings for {transport}', ['transport' => $transport])],];
$form_defs['placeholder']['save'] = fn (string $transport, string $form_name) => [$form_name, SubmitType::class,
['label' => _m('Save notification settings for {transport}', ['transport' => $transport])], ];
Event::handle('AddNotificationTransport', [&$form_defs]);
unset($form_defs['placeholder']);
@ -334,7 +326,7 @@ class UserPanel extends Controller
$tabbed_forms = [];
foreach ($form_defs as $transport_name => $f) {
unset($f['save']);
$form = Form::create($f);
$form = Form::create($f);
$tabbed_forms[$transport_name] = $form;
$form->handleRequest($request);
@ -360,15 +352,13 @@ class UserPanel extends Controller
}
}
$tabbed_forms = F\map($tabbed_forms, fn($f) => $f->createView());
$tabbed_forms = F\map($tabbed_forms, fn ($f) => $f->createView());
return $tabbed_forms;
}
/**
* Controller for defining the ordering of a users' languages
*
* @param Request $request
* @return array
* @throws NoLoggedInUser
* @throws RedirectException
* @throws ServerException
@ -386,18 +376,18 @@ class UserPanel extends Controller
$form_entries[] = ['save_language_order', SubmitType::class, []];
$form_entries[] = ['go_back', SubmitType::class, ['label' => _m('Return to settings page')]];
$form = Form::create($form_entries);
$form = Form::create($form_entries);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var SubmitButton $button */
$button = $form->get('go_back');
$button = $form->get('go_back');
$go_back = $button->isClicked();
$data = $form->getData();
$data = $form->getData();
asort($data); // Sort by the order value
$data = array_keys($data); // This keeps the order and gives us a unique number for each
foreach ($data as $order => $locale) {
$lang = Language::getFromLocale($locale);
$lang = Language::getByLocale($locale);
$actor_lang = DB::getReference('actor_language', ['actor_id' => $user->getId(), 'language_id' => $lang->getId()]);
$actor_lang->setOrdering($order + 1);
}
@ -412,7 +402,7 @@ class UserPanel extends Controller
return [
'_template' => 'settings/sort_languages.html.twig',
'form' => $form->createView(),
'form' => $form->createView(),
];
}
}

View File

@ -108,7 +108,7 @@ class ActorLanguage extends Entity
'select l from actor_language al join language l with al.language_id = l.id where al.actor_id = :id order by al.ordering ASC',
['id' => $id],
),
) ?: [Language::getFromLocale(Common::config('site', 'language'))];
) ?: [Language::getByLocale(Common::config('site', 'language'))];
}
public static function schemaDef(): array

View File

@ -21,6 +21,8 @@ declare(strict_types = 1);
namespace App\Entity;
use App\Core\Cache;
use App\Core\DB\DB;
use App\Core\Entity;
use Component\Tag\Tag;
use DateTimeInterface;
@ -91,6 +93,25 @@ class ActorTagBlock extends Entity
// @codeCoverageIgnoreEnd
// }}} Autocode
public static function cacheKey(int $actor_id)
{
return "actor-tag-blocks-{$actor_id}";
}
public static function getByActorId(int $actor_id)
{
return Cache::getList(self::cacheKey($actor_id), fn () => DB::findBy('actor_tag_block', ['blocker' => $actor_id]));
}
/**
* Check whether $actor_tag is considered blocked by one of
* $actor_tag_blocks
*/
public static function checkBlocksActorTag(ActorTag $actor_tag, array $actor_tag_blocks): bool
{
return F\some($actor_tag_blocks, fn ($ntb) => ($ntb->getUseCanonical() && $actor_tag->getCanonical() === $ntb->getCanonical()) || $actor_tag->getTag() === $ntb->getTag());
}
public static function schemaDef(): array
{
return [

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
@ -62,8 +64,8 @@ class Group extends Entity
private ?string $mainpage;
private ?int $join_policy;
private ?int $force_scope;
private \DateTimeInterface $created;
private \DateTimeInterface $modified;
private DateTimeInterface $created;
private DateTimeInterface $modified;
public function setId(int $id): self
{
@ -271,7 +273,7 @@ class Group extends Entity
return Actor::getById($this->getId());
}
public static function getFromNickname(string $nickname, ?Actor $actor = null): ?self
public static function getByNickname(string $nickname, ?Actor $actor = null): ?self
{
$nickname = Nickname::normalize($nickname, check_already_used: false);
$group = null;

View File

@ -108,7 +108,7 @@ class Language extends Entity
// @codeCoverageIgnoreEnd
// }}} Autocode
public static function getFromId(int $id): self
public static function getById(int $id): self
{
return Cache::getHashMapKey(
map_key: 'languages-id',
@ -117,7 +117,7 @@ class Language extends Entity
);
}
public static function getFromLocale(string $locale): self
public static function getByLocale(string $locale): self
{
return Cache::getHashMapKey(
'languages',
@ -126,9 +126,9 @@ class Language extends Entity
);
}
public static function getFromNote(Note $note): self
public static function getByNote(Note $note): self
{
return self::getFromId($note->getLanguageId());
return self::getById($note->getLanguageId());
}
public static function getLanguageChoices(): array
@ -159,7 +159,7 @@ class Language extends Entity
$key = array_key_first($preferred_language_choices);
$locale = $preferred_language_choices[$key];
unset($preferred_language_choices[$key], $language_choices[$key]);
$short_display = self::getFromLocale($locale)->getShortDisplay();
$short_display = self::getByLocale($locale)->getShortDisplay();
$preferred_language_choices[$short_display] = trim($locale);
$language_choices[$short_display] = trim($locale);
}

View File

@ -216,19 +216,19 @@ class Note extends Entity
return Avatar::getUrl($this->getActorId(), $size);
}
public static function getFromId(int $note_id): self
public static function getById(int $note_id): self
{
return Cache::get("note-{$note_id}", fn () => DB::findOneBy('note', ['id' => $note_id]));
}
public function getNoteLanguageShortDisplay(): string
{
return Language::getFromId($this->language_id)->getShortDisplay();
return Language::getById($this->language_id)->getShortDisplay();
}
public function getLanguageLocale(): string
{
return Language::getFromId($this->language_id)->getLocale();
return Language::getById($this->language_id)->getLocale();
}
public static function getAllNotesByActor(Actor $actor): array
@ -330,7 +330,7 @@ class Note extends Entity
{
$rendered = null;
$mentions = [];
Event::handle('RenderNoteContent', [$this->getContent(), $this->getContentType(), &$rendered, &$mentions, $this->getActor(), Language::getFromId($this->getLanguageId())->getLocale()]);
Event::handle('RenderNoteContent', [$this->getContent(), $this->getContentType(), &$rendered, &$mentions, $this->getActor(), Language::getById($this->getLanguageId())->getLocale()]);
$mentioned = [];
foreach ($mentions as $mention) {
foreach ($mention['mentioned'] as $m) {

View File

@ -118,7 +118,7 @@ class NoteTag extends Entity
return "note-tags-{$note_id}";
}
public static function getFromNoteId(int $note_id): array
public static function getByNoteId(int $note_id): array
{
return Cache::getList(self::cacheKey($note_id), fn () => DB::dql('select nt from note_tag nt join note n with n.id = nt.note_id where n.id = :id', ['id' => $note_id]));
}

View File

@ -111,13 +111,14 @@ class NoteTagBlock extends Entity
return "note-tag-blocks-{$actor_id}";
}
public static function getFromActorId(int $actor_id)
public static function getByActorId(int $actor_id)
{
return Cache::getList(self::cacheKey($actor_id), fn () => DB::findBy('note_tag_block', ['blocker' => $actor_id]));
}
/**
* Check whether $note_tag should
* Check whether $note_tag is considered blocked by one of
* $note_tag_blocks
*/
public static function checkBlocksNoteTag(NoteTag $note_tag, array $note_tag_blocks): bool
{

View File

@ -355,7 +355,7 @@ abstract class Formatting
$group_matches = self::findMentionsRaw($text, '!');
foreach ($group_matches as $group_match) {
$nickname = Nickname::normalize($group_match[0], check_already_used: false, check_is_allowed: false);
$group = Group::getFromNickname($nickname, $actor);
$group = Group::getByNickname($nickname, $actor);
if (!$group instanceof Group) {
continue;