anker/src/Entity/ChineseProductionNote.php

91 lines
2.6 KiB
PHP

<?php
namespace App\Entity;
use App\Utils\Japanese;
class ChineseProductionNote extends Note
{
const MODEL_NAME = 'Chinese production';
const DECK = '汉语::汉字';
private ?array $mediaInfo = [];
private ?Term $term = null;
public static function fromNote(Note $origNote, Term $term): self
{
$slNote = new self();
foreach (get_object_vars($origNote) as $prop => $value) {
$slNote->$prop = $value;
}
// Related fields are updated using the setter
$slNote->setTerm($term);
// Reset relations and basic data
$slNote->id = null;
$slNote->model = self::MODEL_NAME;
$slNote->cardIds = [];
return $slNote;
}
// -------------------------------------------------- Getters & setters ---
public function getTerm(): Term
{
return $this->term;
}
public function setTerm(Term $term): static
{
$hanzi = Japanese::getKanjiList($term->getKanji());
$pinyin = explode(' ', $term->getReading());
foreach ($pinyin as $key => $iPinyin) {
$color = ChineseTone::fromPinyin($iPinyin)->getColor();
$spanTmpl = '<span style="color: %s;">%s</span>';
$hanzi[$key] = sprintf($spanTmpl, $color, $hanzi[$key]);
$pinyin[$key] = sprintf($spanTmpl, $color, $iPinyin);
}
if (!isset($term->audio)) dd($term);
$this->fields['VocabHanzi'] = implode('', $hanzi);
$this->fields['VocabPinyin'] = implode(' ', $pinyin);
$this->fields['VocabDef'] = $term->toAnkiVocabDef();
$this->fields['VocabAudio'] = $term->audio;
$this->fields['SentHanzi'] = Note::stringHighlight(
$this->fields['SentHanzi'],
$term->getKanji(),
);
$this->term = $term;
return $this;
}
// ------------------------------------------------------- Anki-related ---
/** @param array<string, string> $noteInfo */
public static function fromAnki(array $noteInfo): static
{
$note = parent::fromAnki($noteInfo);
if ($note->getModel() !== self::MODEL_NAME) {
throw new \Exception('Trying to parse wrong model');
}
$note->mediaInfo = Note::parseMediaInfo($note->fields['Notes']);
// Set VocabKanji field
$note->term = Term::fromNoteFields($note->fields)[0] ?? null;
if ($note->term === null) {
throw new \Exception("Couldn't get term for Listening card");
}
return $note;
}
// ---------------------------------------------------- Derived methods ---
}