code: private function checkHierarchyIntegrity(InvoiceInterface $invoice)
      {
          // [ Invoice <-> Sale <-> Shipment ] integrity
          if (null !== $shipment = $invoice->getShipment()) {
              if ($invoice->getSale() !== $shipment->getSale()) {
                  throw new ValidationFailedException();
              }
  
              // Credit <-> Return
              if (InvoiceTypes::isCredit($invoice) && !$shipment->isReturn()) {
                  throw new ValidationFailedException();
              }
  
              // Invoice <-> Shipment
              if (InvoiceTypes::isInvoice($invoice) && $shipment->isReturn()) {
                  throw new ValidationFailedException();
              }
          }
      }
docs: Check the hierarchy integrity.
  
  @param InvoiceInterface $invoice
  
  @throws ValidationFailedException